String Methods in JS
String Methods in JS
length
Returns the length of a string.
let str = "Hello World";
console.log(str.length); // 11
2. toUpperCase()
Converts the string to uppercase.
let str = "hello";
console.log(str.toUpperCase()); // "HELLO"
3. toLowerCase()
Converts the string to lowercase.
let str = "HELLO";
console.log(str.toLowerCase()); // "hello"
4. charAt(index)
Returns the character at the specified index.
let str = "JavaScript";
console.log(str.charAt(4)); // "S"
5. indexOf(substring)
Returns the index of the first occurrence of a substring.
let str = "Hello World";
console.log(str.indexOf("World")); // 6
6. includes(substring)
Checks if a string contains a substring.
let str = "Hello World";
console.log(str.includes("World")); // true
7. substring(start, end)
Returns the part of the string between start and end.
let str = "JavaScript";
console.log(str.substring(0, 4)); // "Java"
8. slice(start, end)
Similar to substring(), but supports negative indices.
let str = "JavaScript";
console.log(str.slice(-6)); // "Script"
9. replace(search, replacement)
Replaces a substring with another string.
let str = "Hello World";
console.log(str.replace("World", "JavaScript")); // "Hello JavaScript"
10. split(separator)
Splits a string into an array based on a separator.
let str = "red,green,blue";
console.log(str.split(",")); // ["red", "green", "blue"]
11. trim()
Removes whitespace from both ends of the string.
let str = " Hello ";
console.log(str.trim()); // "Hello"