December 20, 2022
Estimated Post Reading Time ~

JavaScript string methods are used to manipulate strings.

JavaScript string methods are used to manipulate strings.
Here are 8 of the most commonly used string methods and their examples:

1. length() 
This method returns the length of a string: 
Example: 
let str = "Hello World"; 
console.log(str.length); //outputs 11

2. indexOf()
This method searches for a specified value in a string and returns the position of the match: 
Example: 
let str = "Hello World"; 
console.log(str.indexOf("World")); //outputs 6

3. substring() This method extracts characters from a string between two specified indices, and returns the new sub-string: 
Example: 
let str = "Hello World"; 
console.log(str.substring(6, 11)); //outputs "World"

4. replace() 
This method searches a string for a specified value and replaces it with a new value: Example: 
let str = "Hello World"; 
console.log(str.replace("World", "there")); //outputs "Hello there"

5. charAt() 
The charAt() method returns the character at the specified index in a string: Example: 
let str = 'Hello World'; 
console.log(str.charAt(0)) ; // Outputs "H"

6. concat() 
The concat() method combines two or more strings and returns a new string: Example: 
let str1 = 'Hello'; 
let str2 = 'World'; 
console.log(str1.concat(' ', str2)); // Outputs "Hello World"

7. includes() 
The includes() method checks if a string contains a specified string/character: Example: 
let str = 'Hello World'; 
console.log(str.includes('World')) ; // Outputs true

8. endsWith() 
This method checks whether a string ends with the characters of a specified string, returning true or false. 
For example: 
let str = 'Hello World'; 
console.log(str.endsWith('orld')); // Output: true


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.