JavaScript String Methods

JavaScript provides various built-in methods to perform operations on strings. Here are some commonly used string methods:

1. charAt()

Returns the character at a specified index.


const str = 'JavaScript';
console.log(str.charAt(4)); // 'S'

            

2. concat()

Joins two or more strings and returns a new string.


const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2)); // 'Hello World'

            

3. includes()

Checks if a string contains a specified value and returns a boolean.


const str = 'JavaScript is awesome';
console.log(str.includes('awesome')); // true

            

4. indexOf()

Returns the index of the first occurrence of a specified value in a string.


const str = 'JavaScript is fun';
console.log(str.indexOf('fun')); // 15

            

5. lastIndexOf()

Returns the index of the last occurrence of a specified value in a string.


const str = 'JavaScript is fun and JavaScript is powerful';
console.log(str.lastIndexOf('JavaScript')); // 33

            

6. replace()

Searches for a specified value and replaces it with another value.


const str = 'JavaScript is fun';
console.log(str.replace('fun', 'amazing')); // 'JavaScript is amazing'

            

7. slice()

Extracts a section of a string and returns it as a new string.


const str = 'JavaScript is great';
console.log(str.slice(0, 10)); // 'JavaScript'

            

8. split()

Splits a string into an array of substrings based on a specified delimiter.


const str = 'JavaScript,Python,Ruby';
console.log(str.split(',')); // ['JavaScript', 'Python', 'Ruby']

            

9. toLowerCase()

Converts all characters in a string to lowercase.


const str = 'JavaScript is AWESOME';
console.log(str.toLowerCase()); // 'javascript is awesome'

            

10. toUpperCase()

Converts all characters in a string to uppercase.


const str = 'JavaScript is awesome';
console.log(str.toUpperCase()); // 'JAVASCRIPT IS AWESOME'

            

11. trim()

Removes whitespace from both ends of a string.


const str = '   JavaScript is fun!   ';
console.log(str.trim()); // 'JavaScript is fun!'