Skip to content

JavaScript String Methods

JavaScript strings are immutable, meaning their content cannot be changed once created. String methods operate on a string and return a new string or a different value, without modifying the original string. This section covers some of the most common and useful string methods.

Finding Substrings: indexOf(), lastIndexOf(), includes(), startsWith(), endsWith()

Section titled “Finding Substrings: indexOf(), lastIndexOf(), includes(), startsWith(), endsWith()”

Returns the index of the first occurrence of searchValue within the string. If not found, returns -1. fromIndex is an optional starting position for the search.

const text = "Hello world, welcome to the world!";
console.log(text.indexOf("world")); // Output: 6
console.log(text.indexOf("world", 10)); // Output: 29 (starts searching from index 10)
console.log(text.indexOf("galaxy")); // Output: -1

Similar to indexOf(), but returns the index of the last occurrence, searching backwards from fromIndex (or end of string if fromIndex is omitted).

console.log(text.lastIndexOf("world")); // Output: 29

Checks if a string contains searchValue. Returns true or false. More readable for simple presence checks.

console.log(text.includes("welcome")); // Output: true
console.log(text.includes("galaxy")); // Output: false

Checks if a string starts with searchValue. position is an optional starting position. Returns true or false.

console.log(text.startsWith("Hello")); // Output: true
console.log(text.startsWith("world", 6)); // Output: true (checks if string from index 6 starts with "world")

Checks if a string ends with searchValue. length is an optional length of the string to consider. Returns true or false.

console.log(text.endsWith("world!")); // Output: true
console.log(text.endsWith("welcome", 20)); // Output: true (considers first 20 chars: "Hello world, welcome")

Extracting String Parts: slice(), substring(), substr() (Legacy)

Section titled “Extracting String Parts: slice(), substring(), substr() (Legacy)”

Extracts a section of a string and returns it as a new string. startIndex is inclusive, endIndex is exclusive. Negative indices count from the end of the string.

const fruitStr = "Apple, Banana, Kiwi";
console.log(fruitStr.slice(7, 13)); // Output: "Banana"
console.log(fruitStr.slice(7)); // Output: "Banana, Kiwi" (to the end)
console.log(fruitStr.slice(-4)); // Output: "Kiwi" (last 4 chars)
console.log(fruitStr.slice(-12, -6)); // Output: "Banana"

Similar to slice(), but if startIndex is greater than endIndex, they are swapped. Negative indices are treated as 0.

console.log(fruitStr.substring(7, 13)); // Output: "Banana"
console.log(fruitStr.substring(13, 7)); // Output: "Banana" (indices swapped)
console.log(fruitStr.substring(-5, 13)); // Output: "Apple, Banana" (negative index treated as 0)

substr(startIndex[, length]) - Legacy/Deprecated

Section titled “substr(startIndex[, length]) - Legacy/Deprecated”

Extracts a substring starting at startIndex with a specified length. Note: This method is considered a legacy feature in ECMAScript and its use is discouraged. slice() or substring() are preferred.

// console.log(fruitStr.substr(7, 6)); // Output: "Banana" (use slice or substring instead)

Replacing String Content: replace(), replaceAll()

Section titled “Replacing String Content: replace(), replaceAll()”

Returns a new string with some or all matches of searchValue replaced by replacementValue. If searchValue is a string, only the first occurrence is replaced. If searchValue is a regular expression with the global (g) flag, all occurrences are replaced.

const message = "Please visit Microsoft! Microsoft is great.";
console.log(message.replace("Microsoft", "W3Schools")); // Output: "Please visit W3Schools! Microsoft is great."
console.log(message.replace(/Microsoft/g, "W3Schools")); // Output: "Please visit W3Schools! W3Schools is great."

replaceAll(searchValue, replacementValue) (ES2021)

Section titled “replaceAll(searchValue, replacementValue) (ES2021)”

Returns a new string with all occurrences of searchValue replaced by replacementValue. searchValue can be a string or a non-global regular expression.

console.log(message.replaceAll("Microsoft", "Google")); // Output: "Please visit Google! Google is great."

Changing Case: toUpperCase(), toLowerCase()

Section titled “Changing Case: toUpperCase(), toLowerCase()”

toUpperCase(): Converts a string to uppercase.

const greeting = "Hello World!";
console.log(greeting.toUpperCase()); // Output: "HELLO WORLD!"

toLowerCase(): Converts a string to lowercase.

console.log(greeting.toLowerCase()); // Output: "hello world!"

Concatenating Strings: concat() and + operator / Template Literals

Section titled “Concatenating Strings: concat() and + operator / Template Literals”

Joins two or more strings and returns a new string.

const str1 = "Hello";
const str2 = " ";
const str3 = "World";
console.log(str1.concat(str2, str3, "!")); // Output: "Hello World!"

The + operator or template literals are generally more common and often more readable for concatenation:

console.log(str1 + str2 + str3 + "!"); // Output: "Hello World!"
console.log(`${str1}${str2}${str3}!`); // Output: "Hello World!" (using template literals)

Trimming Whitespace: trim(), trimStart(), trimEnd()

Section titled “Trimming Whitespace: trim(), trimStart(), trimEnd()”

trim(): Removes whitespace from both ends of a string.

const paddedText = " Hello, World! ";
console.log(paddedText.trim()); // Output: "Hello, World!"

trimStart() or trimLeft() (ES2019): Removes whitespace from the beginning of a string.

console.log(paddedText.trimStart()); // Output: "Hello, World! "

trimEnd() or trimRight() (ES2019): Removes whitespace from the end of a string.

console.log(paddedText.trimEnd()); // Output: " Hello, World!"

Padding Strings: padStart(), padEnd() (ES2017)

Section titled “Padding Strings: padStart(), padEnd() (ES2017)”

Pads the current string from the start with a given string (repeatedly, if needed) until the resulting string reaches the targetLength. Default padString is a space.

const numStr = "5";
console.log(numStr.padStart(4, "0")); // Output: "0005"
console.log("abc".padStart(5)); // Output: " abc"

Pads the current string from the end.

console.log(numStr.padEnd(4, "*")); // Output: "5***"
console.log("abc".padEnd(5, ".")); // Output: "abc.."

Extracting String Characters: charAt(), charCodeAt(), Property Access

Section titled “Extracting String Characters: charAt(), charCodeAt(), Property Access”

Returns the character at a specified index in a string.

const myString = "HELLO";
console.log(myString.charAt(0)); // Output: "H"

Returns the Unicode (UTF-16 code unit) of the character at a specified index.

console.log(myString.charCodeAt(0)); // Output: 72 (Unicode for 'H')

Strings can be treated like read-only arrays to access characters by index. This is now widely supported and generally safe for reading.

console.log(myString[1]); // Output: "E"

Note: Attempting to assign to a character position (e.g., myString[0] = "J";) will not change the string (due to immutability) and will not cause an error in non-strict mode (may cause an error in strict mode depending on the engine).

Splits a string into an array of substrings, using separator to determine where to make the splits. limit is an optional integer specifying the maximum number of splits.

const csvData = "apple,banana,cherry,date";
console.log(csvData.split(",")); // Output: ["apple", "banana", "cherry", "date"]
console.log("Hello World".split(" ")); // Output: ["Hello", "World"]
console.log("test".split("")); // Output: ["t", "e", "s", "t"] (splits into individual characters)
// If separator is omitted or not found, returns an array with the original string as its only element.
console.log(" одиночный ".split()); // Output: [" одиночный "]

This covers many common string methods. For a comprehensive list, descriptions, and examples of all string properties and methods, refer to the MDN Web Docs on String.