Locating Substrings
To find the position of a specific character or sequence within a string, use indexOf(). This method returns the index of the first occurrence or -1 if the value is not found.
const message = "Learn, build, and share";
// Finding the first occurrence of 'b'
const firstB = message.indexOf("b"); // returns 7
// Starting search from index 10
const nextA = message.indexOf("a", 10); // returns 18
Accessing Individual Chraacters
The charAt() method retrieves the character at a specific index. Modern JavaScript also supports bracket notation for the same purpose.
const label = "Frontend";
console.log(label.charAt(4)); // "t"
console.log(label[0]); // "F"
Extracting Portions of a String
JavaScript provides several ways to extract parts of a string: slice(), substring(), and substr().
slice(start, end): Extracts fromstartup to, but not including,end.substring(start, end): Operates similarly to slice but handles negative indices different (treating them as 0).substr(start, length): Extracst a specific number of characters starting from a specified index.
const sequence = "Modern Web Development";
console.log(sequence.slice(0, 6)); // "Modern"
console.log(sequence.substring(7, 10)); // "Web"
console.log(sequence.substr(11, 11)); // "Development"
Splitting and Replacing
The split() method converts a string into an array based on a delimiter. The replace() method searches for a pattern and substitutes it with a new string.
const csv = "red,green,blue";
// Convert string to array
const colors = csv.split(","); // ["red", "green", "blue"]
// Replace content (case-sensitive by default)
const updatedCsv = csv.replace("red", "yellow"); // "yellow,green,blue"
Common String Method Reference
| Method | Description |
|---|---|
charAt(index) |
Returns the character at a specific index. |
charCodeAt(index) |
Returns the Unicode value of the character at a specific index. |
concat(str1, str2) |
Combines two or more strings into one. |
indexOf(value, start) |
Returns the index of the first occurrence of a substring. |
lastIndexOf(value, start) |
Returns the index of the last occurrence of a substring. |
match(regexp) |
Matches a string against a regular expression. |
replace(search, new) |
Replaces a pattern with a new value. |
search(regexp) |
Executes a search for a match in a string. |
slice(start, end) |
Extracts a section of a string. |
split(separator) |
Breaks a string into an array of substrings. |
substr(start, length) |
Extracts a number of characters starting at a specific index. |
substring(start, end) |
Extracts characters between two indices. |
toLowerCase() |
Converts the entire string to lowercase. |
toUpperCase() |
Converts the entire string to uppercase. |
trim() |
Removes whitespace from both ends of a string. |
valueOf() |
Returns the primitive value of the string object. |