JavaScript provides a variety of built-in methods for working with strings, allowing you to manipulate and extract information from strings easily. Here are some commonly used string methods in JavaScript:
Returns the length of a string.
let str = "Hello, world!";
console.log(str.length); // Output: 13
Returns the character at the specified index.
let str = "Hello, world!";
console.log(str.charAt(0)); // Output: "H"
console.log(str.charAt(7)); // Output: "w"
Converts the string to uppercase.
let str = "Hello, world!";
console.log(str.toUpperCase()); // Output: "HELLO, WORLD!"
Converts the string to lowercase.
let str = "Hello, world!";
console.log(str.toLowerCase()); // Output: "hello, world!"
Returns the index of the first occurrence of a specified substring, or -1 if the substring is not found.
let str = "Hello, world!";
console.log(str.indexOf("world")); // Output: 7
console.log(str.indexOf("foo")); // Output: -1
Returns a substring based on the specified start and end indices. The endIndex is optional and defaults to the end of the string.
let str = "Hello, world!";
console.log(str.substring(0, 5)); // Output: "Hello"
console.log(str.substring(7)); // Output: "world!"
Similar to substring() , but also supports negative indices, which count from the end of the string.
let str = "Hello, world!";
console.log(str.slice(7)); // Output: "world!"
console.log(str.slice(-6, -1)); // Output: "world"
Splits the string into an array of substrings based on the specified separator.
let str = "Hello, world!";
console.log(str.split(", ")); // Output: ["Hello", "world!"]
Removes whitespace from both ends of the string.
let str = " Hello, world! ";
console.log(str.trim()); // Output: "Hello, world!"
Replaces occurrences of a specified substring with another substring.
let str = "Hello, world!";
console.log(str.replace("world", "JavaScript")); // Output: "Hello, JavaScript!"
These are just a few of the many string methods available in JavaScript. Understanding and utilizing these methods can greatly enhance your ability to work with strings in your JavaScript applications.