Working with Strings in JavaScript: 14 Must-Know Methods
Hey, JavaScript learners! Strings are an important part of coding, and these methods will help you work with them effortlessly .
- length
Gives the number of characters in a string.
let str = "Hello, world!";
console.log(str.length); // 132. toUpperCase()
Converts the string to all uppercase letters.
let str = "hello";
console.log(str.toUpperCase()); // "HELLO"3. toLowerCase()
Converts the string to all lowercase letters.
let str = "HELLO";
console.log(str.toLowerCase()); // "hello"4. indexOf()
Finds the first position of a specified value in the string.
let str = "Hello, world!";
console.log(str.indexOf("world")); // 75. lastIndexOf()
Finds the last position of a specified value in the string.
let str = "Hello, world! Hello!";
console.log(str.lastIndexOf("Hello")); // 146. includes()
Checks if a string contains a specified value (true/false).
let str = "Hello, world!";
console.log(str.includes("world")); // true7. slice()
Extracts a part of the string and returns it as a new string.
let str = "Hello, world!";Get Azhar Farhan’s stories in your inbox
Join Medium for free to get updates from this writer.
console.log(str.slice(7, 12)); // "world"
8. substring()
Similar to slice(), it extracts characters between two indices.
let str = "Hello, world!";
console.log(str.substring(7, 12)); // "world"9. replace()
Replaces a specified value with another value in the string.
let str = "Hello, world!";
console.log(str.replace("world", "JS")); // "Hello, JS!"10. split()
Splits a string into an array of substrings using a specified separator.
let str = "apple,banana,cherry";
console.log(str.split(",")); // ["apple", "banana", "cherry"]11. trim()
Removes whitespace from both ends of a string.
let str = " hello ";
console.log(str.trim()); // "hello"12. charAt()
Returns the character at a specified index in the string.
let str = "Hello";
console.log(str.charAt(1)); // "e"13. startsWith()
Checks if a string begins with a specified value (true/false).
let str = "Hello, world!";
console.log(str.startsWith("Hello")); // true14 .endsWith()
Checks if a string ends with a specified value (true/false).
let str = "Hello, world!";
console.log(str.endsWith("world!")); // true





