How to Remove a Substring from a String in JavaScript
Table of Contents
Sometimes when you are working with strings, you want to remove a substring from one of them.
This is because the string might contain some characters or be in a format that you want to change.
Either way, in this post, we'll learn how to remove a substring from a string using JavaScript.
How to remove a substring from a string in JavaScript
First, let's start with an example string:
JAVASCRIPTconst string = "Hello World";
Let's say that you want to remove the word World
from the string.
The easiest way to accomplish this is by using the built-in replace()
method.
JAVASCRIPTconst string = "Hello World";
const newString = string.replace("World", "");
console.log(newString);
BASHHello
The replace()
method only removes the first occurrence of the substring.
If you want to remove all occurrences of the substring, you can use the replaceAll()
method.
JAVASCRIPTconst string = "Hello World World";
const newString = string.replaceAll("World", "");
console.log(newString);
BASHHello
Keep in mind that both the replace
and replaceAll
methods also accept regular expressions to match against, which can be useful when you have more specific needs.
Here's an example of using regex instead of a substring:
JAVASCRIPTconst string = "Hello World World";
const newString = string.replaceAll(/World/g, "");
console.log(newString);
BASHHello
Conclusion
In this post, we learned how to remove a substring from a string using JavaScript.
Simply use the replace()
or replaceAll()
methods to remove a substring from a string, and pass it either your exact substring or a regular expression to match against.
Thanks for reading!
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a Node app using Docker
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API