How to remove characters from a string in JavaScript

Key takeaways:

  • JavaScript provides several built-in methods for removing characters from strings, each with unique functionalities:

    • replace(): Replaces specified characters with a new string or removes them when an empty string is used. To replace all occurrences, combine it with a regular expression and the global flag.

    • slice(): Extracts portions of a string using start and end indices, and can effectively remove parts of the string.

    • split(): Divides a string into an array of substrings based on a separator and optional limit.

    • substr(): Extracts a substring by specifying a starting index and length.

    • substring(): Extracts a substring from a start index to an end index, excluding the character at the end index.

When working with strings in JavaScript, we may often need to remove certain characters to format text, filter input, or manipulate the data. In this Answer, we’ll explore various ways to remove characters from a string in JavaScript. We’ll cover several methods for eliminating specific characters, using regular expressions, and trimming characters from different string parts.

Fun fact—the longest word:

Did you know, some string operations are tested using absurdly long strings. The chemical name for titin, a protein, contains over 189,000 characters—making it one of the longest words in existence and ideal for testing string operations.

What is a string in JavaScript?

In JavaScript, strings are primitive values that contain a series of characters enclosed in a single (' ') quote, double (" ") quotes or backticks (` `) that are zero-based. Strings are immutable, which means that when a string is modified, the original string doesn’t change, instead we get a new string.

Removing characters from a string

JavaScript provides built-in methods to manipulate the value of a string. With string manipulation, we can modify and transform strings using various techniques, that help us write less code and make our job easier. One of the ways we can manipulate strings is by removing characters from the string.

The following methods can be used to remove characters from a string in JavaScript:

  • The replace() method

  • The slice() method

  • The split() method

  • The substr() method

  • The substring() method

Let’s look at these methods one by one:

Method 1: Using the replace() method

The replace() method returns a new string with its replacement. It takes in two arguments—the first argument is the character to be replaced and the second argument is the character we are replacing it with. To remove the character using the replace() method, we replace the second argument with an empty string.

Syntax

Below is the syntax of the replce() method:

nameOfstring.replace('characterToBeReplaced', 'newCharacter');

where:

  • characterToBeReplaced is the character to be replaced.

  • newCharacter is the character to be replaced with.

Example

Let’s have a code example of the replace() method:

const str = "Hello World";
// replacing H with B
const repStr = str.replace("H", "B"); // "Bello World"
console.log(repStr);
// removing character W
const newStr = str.replace("W", ""); // "Hello orld"
console.log(newStr);

In the above code:

  • Line 4: The replace() method replaces H (first argument) with B (second argument) and returns a new string Bello World.

  • Line 9: The replace() method removes the W character and returns a new string Hello orld.

Note: The replace() method only removes the first occurrence of the specified character. To remove all occurrences, we can use a regular expression with the global (g) flag. You can explore more about the replace() method here: What is replace() in JavaScript?

Method 2: The replace() method with a regular expression

We can also use the replace() method with regular expressions. The regular expression is used along with the global property, g. This combination selects all occurrences of the string and allows us to remove them all.

Syntax

Below is the syntax of the replce() method with a regular expression:

nameOfstring.replace( /regularExpression/g, 'newCharacter');

where:

  • /regularExpression/ is the regular expression.

  • g is the global flag to replace all matching characters.

  • newCharacter is the character to be replaced with.

Example

Let’s have a code example of the replace() method with a regular expression:

const str = "The day is bright, it's bright and fair.";
// replacing bright with amazing
const repStr = str.replace(/bright/g, "amazing");
console.log(repStr); //The day is amazing, it's amazing and fair.
// removing bright
const remStr = str.replace(/bright/g, "");
console.log(remStr); //The day is , it's and fair.

In the above code:

  • Line 3: The replace() method selects all occurrences of the word bright and replaces them with amazing.

  • Line 8: The replace() method removes all occurrences of the word bright.

Method 3: The slice() method

This method extracts a portion of the string. It takes in two parameters—the start index and the end index and returns the string between them.

Syntax

Below is the syntax of the slice() method:

nameOfString.slice(startIndex, endIndex);

where:

  • startIndex is the index from the string should start. The default value for startIndex is the start of the string.

  • endIndex is the index to the string should end. The default value for endIndex is the length of the string.

Example

Let’s have a code example of the slice() method:

const subject = "mathematics";
// zero arguments
const text1 = subject.slice();
console.log(text1); // mathematics
// one argument
const text2 = subject.slice(2);
console.log(text2); // thematics
// two arguments
let text3 = subject.slice(1, 3);
console.log(text3); // at
// negative value
let text4 = subject.slice(-3);
console.log(text4); // ics
// default for end index
let text5 = subject.slice(2, subject.length-1);
console.log(text5); // thematic

In the above code:

  • Line 4: When the slice() method has zero arguments, it returns a copy of the string.

  • Line 8: When the slice() method contains one argument, this argument represents the start index. Therefore, the extraction started from the start index t which is the third character to the end of the array excluding the element at the end index, so the extracted item is thematics.

  • Line 12: When the slice() method contains two arguments, it extracts from the start index to the end index. Here, the extraction started from a which is the seventh character and stopped at t which is the eighth character.

  • Line 16: When given a negative index, the slice() method counts backward from the end of the string to find the indices.

  • Line 20: To remove the last character using slice() method, we pass string.length-1 as the end index. The default for endIndex is the length of the string.

You can explore more about the slice() method here: What is the array.slice() method in JavaScript?

Method 4: The split() method

This method uses the separator to break up the string into substrings, it can also take up an optional argument that shows the limit of items to be put in the array.

Syntax

Below is the syntax of the split() method:

nameOfString.split(separator, limit);

where:

  • separator is the string or character to divide with the string into substrings.

  • limit is the number of substrings to generate.

Example

Let’s have a code example of the slice() method:

const str = "Hello World class developer";
// divides it into substrings
let text1 = str.split(" ");
// using 2 as the limit
let text4 = str.split(" ",2);
console.log(text1); // [ 'Hello', 'World', 'class', 'developer' ]
console.log(text4); // [ 'Hello', 'World' ]

In the above code:

  • Line 4: The split() method uses the separator (" ") to divide the string into substrings.

  • Line 7: The split() method takes in 2 arguments: the first is an empty string and the second argument is 2 (limit of items to be put in the array).

You can explore more about the split() method here: String split() method in JavaScript

Method 5: The substr() method

This method extracts a portion of the string, it takes in two arguments—the start index and the length of the substring. If the substr() method contains one argument, it extracts from the start index to the end of the string.

Syntax

Below is the syntax of the substr() method:

nameOfString.substr(startIndex, length);

where:

  • startIndex is the index to start the substring.

  • length is the length of the substring.

Example

Let’s have a code example of the substr() method:

const str = "Hello";
let text1 = str.substr(0,4);
console.log(text1); //Hell

Explanation

  • Line 3: The extraction started from the index 0 till index 4 (excluding index 4).

You can explore more about the substr() method here: What is substr() in JavaScript?

Method 6: The substring() method

This method extracts characters from the start index to the end index (excluding the element at the end index).

Syntax

Below is the syntax of the substring() method:

nameOfString.substring(startIndex, endIndex);

Here:

  • startIndex is the index from the string should start. The default value for startIndex is the start of the string.

  • endIndex is the index to the string should end. The default value for endIndex is the length of the string.

Example

Let’s have a code example of the substring() method:

const str = "Hello, World";
// two arguments
let text1 = str.substring(0,4);
// one arguments
let text2 = str.substring(7);
// start index > end index
let text3 = str.substring(5,2);
let text4 = str.substring(2,5);
// the value is less than 0
let text5 = str.substring(-2);
console.log(text1); // Hell
console.log(text2); // World
console.log(text3); // llo
console.log(text4); // llo
console.log(text5); // Hello, World

In the above code:

  • Line 4: The extraction started from the index 0 till index 4 (excluding index 4).

  • Line 6: The extraction is started from the index 7 till the end.

  • Lines 9–10: If the startIndex is greater than the endIndex, arguments are swapped.

  • Line 13: If the value of the startIndex or endIndex is less than 0, these values are treated as 0.

You can explore more about the substring() method here: How to get a substring in JavaScript

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

How would you remove the first occurrence of the letter l from the string Hello World?

A)

text.replace("l", "");

B)

text.replace(/l/g, "");

C)

text.slice(2);

D)

text.split('l');

Conclusion

Whether you’re removing characters based on patterns, trimming whitespace, or extracting substrings, JavaScript provides powerful tools to get the job done. With practice, you’ll find which method works best for your needs, making string manipulation easier and more effective. By understanding these methods, you’ll have a better handle on string manipulation, making your JavaScript code cleaner and more functional.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do I remove the first 3 characters from a string in JavaScript?

You can use the slice() method to remove the first 3 characters. Here’s how:

let text = "Hello, World!";
let result = text.slice(3);
console.log(result); // "lo, World!"

In this example, slice(3) removes the first 3 characters by starting the slice at index 3.


How do I remove everything after a specific character in JavaScript?

You can use indexOf() to locate the character and then use slice() to get the substring up to that character. For example, to remove everything after the comma:

let text = "Hello, World!";
let result = text.slice(0, text.indexOf(","));
console.log(result); // "Hello"

This finds the position of the comma and slices the string from the beginning up to (but not including) that character.


How do I strip whitespace from a string in JavaScript?

To remove whitespace from the beginning and end of a string, you can use the trim() method. For example:

let text = "   Hello, World!   ";
let result = text.trim();
console.log(result); // "Hello, World!"

If you need to remove whitespace only from the start, use trimStart(), and for the end only, use trimEnd().



Free Resources