JavaScript provides a wide range of string methods that can be used to manipulate and modify strings. Here are 15 commonly used string methods in JavaScript, along with examples and their outputs.
1. length
- Description: Returns the length of a string.
- Example:
str.length;
- Output:
21
2. trim()
- Description: Removes whitespace from both ends of a string.
- Example:
str.trim();
- Output:
"Hello, JavaScript!"
3. toUpperCase()
- Description: Converts a string to uppercase.
- Example:
str.toUpperCase();
- Output:
"HELLO, JAVASCRIPT!"
4. toLowerCase()
- Description: Converts a string to lowercase.
- Example:
str.toLowerCase();
- Output:
"hello, javascript!"
5. charAt()
- Description: Returns the character at a specific index in a string.
- Example:
str.charAt(7);
- Output:
"J"
6. indexOf()
- Description: Finds the first occurrence of a substring in a string.
- Example:
str.indexOf("JavaScript");
- Output:
8
7. includes()
- Description: Checks if a substring is present in a string.
- Example:
str.includes("Hello");
- Output:
true
8. substring()
- Description: Extracts characters between two indices in a string.
- Example:
str.substring(0, 7);
- Output:
"Hello"
9. slice()
- Description: Similar to substring, but allows negative indices.
- Example:
str.slice(2, -2);
- Output:
"Hello, JavaScript"
10. replace()
- Description: Replaces a substring with another string.
- Example:
str.replace("JavaScript", "World");
- Output:
"Hello, World!"
11. split()
- Description: Splits a string into an array by a separator.
- Example:
str.split(" ");
- Output:
["", "", "Hello,", "JavaScript!", "", ""]
12. concat()
- Description: Concatenates two or more strings.
- Example:
str.concat("Let's code!");
- Output:
"Hello, JavaScript!Let's code!"
13. startsWith()
- Description: Checks if a string starts with a specified substring.
- Example:
str.startsWith("Hello");
- Output:
false
(due to leading spaces)
14. endsWith()
- Description: Checks if a string ends with a specified substring.
- Example:
str.endsWith("!");
- Output:
true
15. repeat()
- Description: Repeats a string a specified number of times.
- Example:
str.repeat(2);
- Output:
"Hello, JavaScript!Hello, JavaScript!"
These string methods can be used to perform various operations on strings in JavaScript, making it easier to manipulate and modify text data in your applications.