JavaScript provides built-in string methods that help you manipulate and work with text. You can convert text to uppercase or lowercase, remove unwanted spaces, search for specific words, replace text, and extract parts of a string.
String methods are commonly used in form validation, search features, text processing, and web development.
In this tutorial, you will learn 11 important JavaScript string methods with syntax, practical examples, and outputs.
What Are String Methods in JavaScript?
String methods are built-in functions that perform operations on string values.
For example, the toUpperCase() method converts a string to uppercase.
const message = "Hello JavaScript";
console.log(message.toUpperCase());
Output:
HELLO JAVASCRIPT
Most string methods return a new value without changing the original string because JavaScript strings are immutable.
Before exploring these methods, you can review JavaScript strings to understand string creation, indexing, and length.
toUpperCase() Method
The toUpperCase() method converts all lowercase letters in a string to uppercase.
Syntax:
string.toUpperCase();
Example:
const message = "Welcome to JavaScript";
console.log(message.toUpperCase());
Output:
WELCOME TO JAVASCRIPT
The method converts the letters to uppercase but does not change numbers, spaces, or punctuation.
Practical Example
You can use toUpperCase() to standardize text before comparing it.
const userInput = "javascript";
if (userInput.toUpperCase() === "JAVASCRIPT") {
console.log("The language matches.");
}
Output:
The language matches.
This comparison works regardless of the original letter case for this example.
toLowerCase() Method
The toLowerCase() method converts all uppercase letters in a string to lowercase.
Syntax:
string.toLowerCase();
Example:
const message = "LEARN JAVASCRIPT";
console.log(message.toLowerCase());
Output:
learn javascript
Practical Example
You can convert user input to lowercase before performing a case-insensitive comparison.
const language = "JavaScript";
console.log(language.toLowerCase() === "javascript");
Output:
true
For simple English text, combining toLowerCase() with a comparison makes it easier to compare different capitalization styles.
trim() Method
The trim() method removes whitespace from the beginning and end of a string.
Syntax:
string.trim();
Example:
const username = " Rahul ";
console.log(username.trim());
Output:
Rahul
The spaces surrounding the name are removed, but spaces between words remain.
Practical Example
The trim() method is useful when processing text entered into a form.
const email = " rahul@example.com ";
const cleanedEmail = email.trim();
console.log(cleanedEmail);
Output:
rahul@example.com
There are also trimStart() and trimEnd() methods for removing whitespace from only the beginning or end of a string.
const message = " Hello ";
console.log(message.trimStart());
console.log(message.trimEnd());
Output:
Hello
Hello
includes() Method
The includes() method checks whether a string contains a specified sequence of characters.
It returns true if the text is found and false otherwise.
Syntax:
string.includes(searchString);
Example:
const message = "Learn JavaScript online";
console.log(message.includes("JavaScript"));
console.log(message.includes("Python"));
Output:
true
false
The includes() method is case-sensitive.
const message = "Learn JavaScript";
console.log(message.includes("JavaScript"));
console.log(message.includes("javascript"));
Output:
true
false
Using includes() With a Starting Position
You can provide a second argument to specify the index where the search should begin.
const message = "JavaScript is useful";
console.log(message.includes("JavaScript", 1));
console.log(message.includes("is", 11));
Output:
false
true
The first search starts at index 1, so it does not find the complete word "JavaScript" at index 0.
The second search begins at index 11, where "is" appears.
startsWith() Method
The startsWith() method checks whether a string begins with a specified sequence of characters.
It returns a Boolean value: true or false.
Syntax:
string.startsWith(searchString);
Example:
const website = "Web4Learners";
console.log(website.startsWith("Web"));
console.log(website.startsWith("Learners"));
Output:
true
false
Using startsWith() With a Position
You can provide an optional starting position for the check.
const message = "Learn JavaScript";
console.log(message.startsWith("JavaScript", 6));
Output:
true
The check begins at index 6, where "JavaScript" starts.
endsWith() Method
The endsWith() method checks whether a string ends with a specified sequence of characters.
Syntax:
string.endsWith(searchString);
Example:
const filename = "tutorial.pdf";
console.log(filename.endsWith(".pdf"));
console.log(filename.endsWith(".jpg"));
Output:
true
false
Practical Example
You can use endsWith() to check a filename’s extension.
const filename = "photo.png";
if (filename.endsWith(".png")) {
console.log("PNG file detected.");
} else {
console.log("Different file type.");
}
Output:
PNG file detected.
This is a basic text check, not complete file validation. Real applications may need additional checks because filenames and extensions can be misleading.
Using endsWith() With a Length
The optional second argument specifies how much of the string to consider.
const message = "Learn JavaScript";
console.log(message.endsWith("Learn", 5));
Output:
true
JavaScript checks whether the first five characters, "Learn", end with the specified text.
replace() Method
The replace() method returns a new string in which the first matching substring or pattern is replaced.
Syntax:
string.replace(searchValue, newValue);
Example:
const message = "I like Java";
console.log(message.replace("Java", "JavaScript"));
Output:
I like JavaScript
The original string remains unchanged.
Replacing Only the First Match
When you search using a plain string, replace() changes only the first occurrence.
const message = "Java is popular. Java is powerful.";
console.log(message.replace("Java", "JavaScript"));
Output:
JavaScript is popular. Java is powerful.
Only the first occurrence of "Java" is replaced.
Replacing Text Using a Regular Expression
You can use a regular expression with the global (g) flag to replace all matching occurrences.
const message = "cat, cat, cat";
console.log(message.replace(/cat/g, "dog"));
Output:
dog, dog, dog
This is another way to replace every match, particularly when you need pattern-based matching.
replaceAll() Method
The replaceAll() method returns a new string in which all matching occurrences of a specified substring or pattern are replaced.
Syntax:
string.replaceAll(searchValue, newValue);
Example:
const message = "Java is popular. Java is powerful.";
console.log(message.replaceAll("Java", "JavaScript"));
Output:
JavaScript is popular. JavaScript is powerful.
Unlike replace() with a plain string, replaceAll() replaces every occurrence.
Practical Example
const phoneNumber = "123-456-7890";
console.log(phoneNumber.replaceAll("-", ""));
Output:
1234567890
All hyphens are removed from the returned string.
When using a regular expression with replaceAll(), the expression must have the global (g) flag.
split() Method
The split() method divides a string into an array of substrings using a specified separator.
Syntax:
string.split(separator);
Example:
const languages = "HTML,CSS,JavaScript";
console.log(languages.split(","));
Output:
["HTML", "CSS", "JavaScript"]
The comma acts as the separator, so the result is an array containing three strings.
Splitting a Sentence Into Words
const message = "Learn JavaScript step by step";
console.log(message.split(" "));
Output:
["Learn", "JavaScript", "step", "by", "step"]
The space character separates the sentence into individual words.
Splitting a String Into Characters
If you provide an empty string as the separator, split("") separates the string into UTF-16 code units.
const language = "Code";
console.log(language.split(""));
Output:
["C", "o", "d", "e"]
For Unicode text containing emoji or other characters represented by multiple code units, Array.from(language) or [...language] may be more suitable.
Using split() With a Limit
You can provide an optional second argument to limit the number of returned array elements.
const languages = "HTML,CSS,JavaScript,Python";
console.log(languages.split(",", 2));
Output:
["HTML", "CSS"]
Only the first two array elements are returned.
Learn more about processing the resulting data in the JavaScript arrays tutorial.
substring() Method
The substring() method extracts characters between two specified indexes and returns a new string.
Syntax:
string.substring(startIndex, endIndex);
The starting index is included, while the ending index is excluded.
Example:
const language = "JavaScript";
console.log(language.substring(0, 4));
console.log(language.substring(4, 10));
Output:
Java
Script
The first expression extracts characters from index 0 up to, but not including, index 4. The second extracts characters from index 4 through the end.
Using substring() With One Argument
If you provide only the starting index, the method extracts the remaining characters.
const message = "Welcome to JavaScript";
console.log(message.substring(11));
Output:
JavaScript
Important Behavior of substring()
Negative arguments are treated as 0, and if the first index is greater than the second, the arguments are swapped.
const language = "JavaScript";
console.log(language.substring(4, 0));
console.log(language.substring(-3, 4));
Output:
Java
Java
This behavior differs from slice(), which is often preferred when you want negative indexes to count backward from the end.
slice() Method
The slice() method extracts part of a string and returns it as a new string.
Syntax:
string.slice(startIndex, endIndex);
The starting index is included, while the ending index is excluded.
Example:
const language = "JavaScript";
console.log(language.slice(0, 4));
console.log(language.slice(4, 10));
Output:
Java
Script
Using slice() With One Argument
If you provide only the starting index, slice() extracts the remaining characters.
const message = "Welcome to JavaScript";
console.log(message.slice(11));
Output:
JavaScript
Using Negative Indexes With slice()
Negative indexes count backward from the end of the string.
const language = "JavaScript";
console.log(language.slice(-6));
console.log(language.slice(-6, -3));
Output:
Script
Scr
The index -6 starts six positions from the end. The ending index -3 stops before the last three characters.
Difference Between slice() and substring()
Both methods extract part of a string, but they handle indexes differently.
| Feature | slice() | substring() |
|---|---|---|
| Extracts part of a string | Yes | Yes |
| Ending index excluded | Yes | Yes |
| Supports negative indexes | Yes | No; negatives become 0 |
| Swaps reversed indexes | No | Yes |
| Returns a new string | Yes | Yes |
For example:
const text = "JavaScript";
console.log(text.slice(-6));
console.log(text.substring(-6));
Output:
Script
JavaScript
Use slice() when negative indexes are useful. Use substring() when you prefer its handling of negative and reversed indexes.
JavaScript String Methods Comparison
The following table summarizes the string methods covered in this tutorial.
| Method | Purpose | Example |
|---|---|---|
toUpperCase() | Converts text to uppercase | "hello".toUpperCase() |
toLowerCase() | Converts text to lowercase | "HELLO".toLowerCase() |
trim() | Removes surrounding whitespace | " hi ".trim() |
includes() | Checks whether text exists | "JavaScript".includes("Script") |
startsWith() | Checks the beginning of a string | "Hello".startsWith("He") |
endsWith() | Checks the end of a string | "report.pdf".endsWith(".pdf") |
replace() | Replaces the first match for a plain string | "cat cat".replace("cat", "dog") |
replaceAll() | Replaces all matches | "cat cat".replaceAll("cat", "dog") |
split() | Divides a string into an array | "a,b".split(",") |
substring() | Extracts characters between indexes | "JavaScript".substring(0, 4) |
slice() | Extracts characters, supporting negative indexes | "JavaScript".slice(-6) |
Practical Example Using Multiple String Methods
The following example combines several methods to clean and process a user’s input.
const input = " learn JAVASCRIPT today ";
// Remove surrounding whitespace
const cleaned = input.trim();
// Convert text to lowercase
const normalized = cleaned.toLowerCase();
// Check whether the text contains JavaScript
const hasJavaScript = normalized.includes("javascript");
// Extract the first word
const firstWord = normalized.split(" ")[0];
// Capitalize the first word
const formattedWord =
firstWord.charAt(0).toUpperCase() + firstWord.slice(1);
console.log(normalized);
console.log(hasJavaScript);
console.log(formattedWord);
Output:
learn javascript today
true
Learn
This example shows how multiple string methods can work together to clean text, search for a word, split a sentence, and format part of the result.
Common Mistakes When Using String Methods
Forgetting Parentheses
String methods require parentheses when called.
Incorrect:
const message = "hello";
console.log(message.toUpperCase);
This accesses the method function rather than calling it.
Correct:
console.log(message.toUpperCase());
Output:
HELLO
Expecting String Methods to Change the Original String
String methods return new values instead of modifying the original string.
const message = "hello";
message.toUpperCase();
console.log(message);
Output:
hello
To keep the converted value, assign the result to a variable.
const message = "hello";
const upperMessage = message.toUpperCase();
console.log(upperMessage);
Output:
HELLO
Confusing slice() and substring()
The two methods behave differently with negative indexes and reversed arguments. Remember that slice() supports negative indexes, while substring() treats negative indexes as 0.
Forgetting That Search Methods Are Case-Sensitive
Methods such as includes(), startsWith(), and endsWith() are case-sensitive.
const language = "JavaScript";
console.log(language.includes("javascript"));
Output:
false
If you need a case-insensitive check for ordinary English text, normalize both strings first.
const language = "JavaScript";
const searchText = "javascript";
console.log(
language.toLowerCase().includes(searchText.toLowerCase())
);
Output:
true
Frequently Asked Questions
Which JavaScript string method converts text to uppercase?
The toUpperCase() method converts letters in a string to uppercase.
What is the difference between trim() and split()?
trim() removes whitespace from the beginning and end of a string. split() divides a string into an array of substrings using a separator.
What is the difference between replace() and replaceAll()?
With a plain string search value, replace() replaces only the first occurrence, while replaceAll() replaces every occurrence.
What does includes() return?
The includes() method returns true if the specified sequence is found in the string and false otherwise.
What is the difference between slice() and substring()?
Both extract part of a string. However, slice() supports negative indexes, while substring() treats negative indexes as zero and swaps its arguments if the starting index is greater than the ending index.
Do string methods modify the original string?
No. JavaScript strings are immutable, so these methods return new strings or other values without changing the original string.
How do you remove spaces from a string?
Use trim() to remove whitespace from both ends. Use trimStart() or trimEnd() when you only want to remove whitespace from one side.
What to Learn Next
After learning JavaScript string methods, continue with JavaScript Numbers and Math Methods to understand numeric operations, rounding, random numbers, and mathematical calculations.