How to Remove a Substring from a String in JavaScript

It’s pretty straightforward to remove a substring from a string in JavaScript. There are a few ways to do this. This post covers them.

How to use replace() in JavaScript?

The replace() method searches for a specified value or a regular expression within a string and returns a new string with the specified values replaced. Note that without a global flag, replace() targets only the first occurrence of the specified value.

let originalString = "Hello, world! Welcome to the world of JavaScript."; let newString = originalString.replace("world", "universe"); console.log(newString); // Outputs: "Hello, universe! Welcome to the world of JavaScript."

How to use replaceAll() in JavaScript?

To remove all instances of a substring, employ the replaceAll() method. It functions like replace(), but affects every occurrence of the specified string.

let originalString = "Hello, world! Welcome to the world of JavaScript."; let newString = originalString.replaceAll("world", "universe"); console.log(newString); // Outputs: "Hello, universe! Welcome to the universe of JavaScript."

How to usereplace() with a global regular expression?

When replaceAll() is not available, you can use replace() with a global (g) flag regular expression to achieve the removal of all instances of a substring.

let originalString = "Hello, world! Welcome to the world of JavaScript."; let newString = originalString.replace(/world/g, "universe"); console.log(newString); // Outputs: "Hello, universe! Welcome to the universe of JavaScript."

How to use slice() in JavaScript?

The slice() method can come in handy for removing a substring when its exact position is known. It's especially useful for cutting characters from the start or end of a string.

let originalString = "Hello, world!"; let start = originalString.indexOf("world"); let end = start + "world".length; let newString = originalString.slice(0, start) + originalString.slice(end); console.log(newString); // Outputs: "Hello, !"

By choosing the appropriate method for your needs, whether removing a single occurrence or all instances of a substring, or extracting parts of a string based on their position, you can handle string manipulation tasks more effectively.

The next generation of charts and BI.

Coming soon.

Fast. Opinionated. Collaborative. Local-first. Keyboard centric.
Crafted to the last pixel. We're looking for early alpha users.