Sitemap
Azhar Farhan

Azhar Farhan

Class of The Hacking School-A25. Learning MERN Stack Development

Working with Strings in JavaScript: 14 Must-Know Methods

2 min readMar 26, 2025

Hey, JavaScript learners! Strings are an important part of coding, and these methods will help you work with them effortlessly .

  1. length
    Gives the number of characters in a string.
let str = "Hello, world!";
console.log(str.length); // 13

2. 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")); // 7

5. lastIndexOf()
Finds the last position of a specified value in the string.

let str = "Hello, world! Hello!";
console.log(str.lastIndexOf("Hello")); // 14

6. includes()
Checks if a string contains a specified value (true/false).

let str = "Hello, world!";
console.log(str.includes("world")); // true

7. slice()
Extracts a part of the string and returns it as a new string.

Get Azhar Farhan’s stories in your inbox

Join Medium for free to get updates from this writer.

let str = "Hello, world!";
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")); // true

14 .endsWith()
Checks if a string ends with a specified value (true/false).

let str = "Hello, world!";
console.log(str.endsWith("world!")); // true

--

--

Azhar Farhan
Azhar Farhan

Written by Azhar Farhan

Class of The Hacking School-A25. Learning MERN Stack Development