JavaScript : String Methods

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:

1. length:


Returns the length of a string.


let str = "Hello, world!";
console.log(str.length);  // Output: 13

 

2. charAt(index):


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"

 

3. toUpperCase():


Converts the string to uppercase.


let str = "Hello, world!";
console.log(str.toUpperCase());  // Output: "HELLO, WORLD!"

 

4. toLowerCase():


Converts the string to lowercase.


let str = "Hello, world!";
console.log(str.toLowerCase());  // Output: "hello, world!"

 

5. indexOf(substring):


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

 

6. substring(startIndex, endIndex):


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!"

 

7. slice(startIndex, endIndex):


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"

 

8. split(separator):


Splits the string into an array of substrings based on the specified separator.


let str = "Hello, world!";
console.log(str.split(", "));  // Output: ["Hello", "world!"]

 

9. trim():


Removes whitespace from both ends of the string.


let str = "   Hello, world!   ";
console.log(str.trim());  // Output: "Hello, world!"

 

10. replace(oldSubstring, newSubstring):


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.