In JavaScript, there are several built-in methods for manipulating strings. Here are some commonly used ones:
length
: returns the length of the string
let str = 'Hello, World!';
console.log(str.length); // Outputs: 13
toUpperCase()
: converts the string to uppercase
let str = 'Hello, World!';
console.log(str.toUpperCase()); // Outputs: HELLO, WORLD!
toLowerCase()
: converts the string to lowercase
let str = 'Hello, World!';
console.log(str.toLowerCase()); // Outputs: hello, world!
indexOf()
: returns the index of the first occurrence of a specified substring
let str = 'Hello, World!';
console.log(str.indexOf('o')); // Outputs: 4
substring()
: returns a substring of the string
let str = 'Hello, World!';
console.log(str.substring(0, 5)); // Outputs: Hello
replace()
: replaces a specified substring with another string
let str = 'Hello, World!';
console.log(str.replace('World', 'Universe')); // Outputs: Hello, Universe!
7.split(): splits a string into an array of substrings
let str = 'Hello, World!';
console.log(str.split(',')); // Outputs: ['Hello', ' World!']
trim()
: removes whitespace from the beginning and end of a string
let str = ' Hello, World! ';
console.log(str.trim()); // Outputs: Hello, World!
9.charAt(): returns the character at a specified index
let str = 'Hello, World!';
console.log(str.charAt(4)); // Outputs: o
endsWith()
: checks if a string ends with a specified substring
let str = 'Hello, World!';
console.log(str.endsWith('!')); // Outputs: true
startsWith()
: checks if a string starts with a specified substring
let str = 'Hello, World!';
console.log(str.startsWith('Hello')); // Outputs: true
12.includes(): checks if a string contains a specified substring
let str = 'Hello, World!';
console.log(str.includes('World')); // Outputs: true
String manipulation is a common task in web development, and understanding string methods is essential for working with strings effectively in JavaScript. The above methods are just a few examples of the many built-in string methods available in JavaScript.