vadnica-logo
Editor My Blog My Services About the Project Telegram O meni O meni

JavaScript Strings

Strings are used to represent and process sequences of characters; they are useful for storing data that can be represented in text form. Some of the most commonly used operations on strings include checking their length, creating and concatenating them using the string operators + and +=, checking for the existence or location of substrings using the indexOf() method, or extracting substrings using the substring() method.

EXAMPLE
RESULT

Strings can be created as primitives, from string literals, or as objects using the String() constructor. Primitive strings and objects share much behavior, but there are other important differences and caveats. String literals can be specified using single or double quotes, which are treated equally, or using backticks.

You can access individual characters in a string in two ways. The first way is with the charAt() method, and the second is to treat the string as an array-like object, where individual characters correspond to numeric indices.

const str = "Banana"[1]; // returns the value "a" from the word Banana

When using square brackets ([]) to access individual characters, attempts to delete or assign values to these properties will fail. Included properties cannot be written to or configured. Inside a string, you can use quotes if they do not match the quotes surrounding the string.

'Using "double" quotes in a "string" surrounded by single quotes.'
"Using 'single' quotes in a 'string' surrounded by double quotes."

Escape Characters

In JavaScript strings, you cannot use the same quotes inside a string as the ones surrounding it, but there is a solution to this problem using an escape character. An escape character is a backslash (\) followed by a quote.

Character Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
\b \b Backspace
\f \f Form feed
\n \n Newline
\r \r Carriage return
\t \t Horizontal tab
\v \v Vertical tab
\0 \0 Null character
\xXX \x41 Hexadecimal character code (XX is a hexadecimal value, e.g., \x41 displays "A")
\uXXXX \u0041 Unicode character code (XXXX is a hexadecimal value, e.g., \u0041 displays "A")

Creating and Basic Properties of Strings

Strings can be created as primitive values (literals) or as objects. Primitive strings are faster and are used in most cases. Every string has a length property that returns the number of characters, as well as numerous methods for searching, modifying, and processing text.

Methods for Processing Strings

Various methods are available for working with strings in JavaScript, divided into several categories:

  1. Searching and indexing characters/substrings (indexOf, includes, search).
  2. Slicing and splitting strings (slice, substring, substr, split).
  3. Changing case and formatting (toUpperCase, toLowerCase, trim, padStart).
  4. Replacing and repeating (replace, repeat).
  5. Concatenation and conversion (concat, toString, charAt, charCodeAt).

Overview of String Methods

The table below shows all major methods and properties of String objects in JavaScript. For each method, the description of operation, syntax, and a concrete code example are provided.

Name Description Syntax Example
length Returns the number of characters in the string. str.length let len = "Banana".length; // 6
indexOf() Returns the index of the first occurrence of a substring (-1 if not found). str.indexOf("substring", startIndex) "Banana".indexOf("na"); // 2
lastIndexOf() Returns the index of the last occurrence of a substring. str.lastIndexOf("substring") "Banana".lastIndexOf("na"); // 4
includes() Returns true if the string contains the substring, otherwise false. str.includes("substring") "Banana".includes("na"); // true
startsWith() Returns true if the string starts with the substring. str.startsWith("substring") "Banana".startsWith("Ba"); // true
endsWith() Returns true if the string ends with the substring. str.endsWith("substring") "Banana".endsWith("na"); // true
search() Returns the index of the first match (supports regular expressions). str.search(regex) "Banana".search(/a/i); // 1
match() Returns an array of matches (supports regular expressions). str.match(regex) "Banana".match(/a/g); // ["a", "a", "a"]
slice() Slices a part of the string (supports negative indices). str.slice(start, end) "Banana".slice(1, 4); // "ana"
substring() Slices a part of the string (does not support negative indices). str.substring(start, end) "Banana".substring(1, 4); // "ana"
substr() Slices a part of the string (start and length) – deprecated. str.substr(start, length) "Banana".substr(1, 3); // "ana"
split() Converts the string into an array, separated by a delimiter. str.split("delimiter") "a,b,c".split(","); // ["a", "b", "c"]
toUpperCase() Returns the string in uppercase. str.toUpperCase() "banana".toUpperCase(); // "BANANA"
toLowerCase() Returns the string in lowercase. str.toLowerCase() "BANANA".toLowerCase(); // "banana"
trim() Removes whitespace from the beginning and end of the string. str.trim() " banana ".trim(); // "banana"
trimStart() Removes whitespace from the beginning of the string. str.trimStart() " banana".trimStart(); // "banana"
trimEnd() Removes whitespace from the end of the string. str.trimEnd() "banana ".trimEnd(); // "banana"
padStart() Adds characters to the start of the string up to a specified length. str.padStart(length, char) "5".padStart(3, "0"); // "005"
padEnd() Adds characters to the end of the string up to a specified length. str.padEnd(length, char) "5".padEnd(3, "0"); // "500"
replace() Replaces the first occurrence of a substring (supports regex). str.replace(old, new) "Banana".replace("B", "b"); // "banana"
replaceAll() Replaces all occurrences of a substring (supports regex). str.replaceAll(old, new) "Banana".replaceAll("a", "A"); // "BAnAnA"
repeat() Repeats the string a specified number of times. str.repeat(count) "Ha".repeat(3); // "HaHaHa"
charAt() Returns the character at a specified index. str.charAt(index) "Banana".charAt(1); // "a"
charCodeAt() Returns the Unicode value of the character at a specified index. str.charCodeAt(index) "Banana".charCodeAt(1); // 97
[index] Access character using square brackets (like an array). str[index] "Banana"[1]; // "a"
concat() Joins two or more strings (less used than +). str.concat(str2, str3) "B".concat("anana"); // "Banana"
toString() Returns the value as a string (default for String objects). str.toString() String(123).toString(); // "123"
valueOf() Returns the primitive value of the string. str.valueOf() "Banana".valueOf(); // "Banana"
Template Literals Allows embedding variables in a string using backticks (`). `String ${variable}` `Hello, ${name}!`; // "Hello, Ana!"
RESULT