How To Remove Word From String In JavaScript
JavaScript
12/07/2021
You've got a string, e.g. Hello World!
, and you want to remove a word from it, e.g. World!
. This job can be done with replace()
as follows:
JAVASCRIPT
const newString = 'Hello World!'.replace(' World!', '')console.log(newString) // 'Hello'
The 1st parameter of this function takes the value you want to replace, and the 2nd parameter the value you want to replace it with. In our case, the latter is an empty string.
Multiple occurrences
How about removing a string that appears multiple times? Instead of a string value, replace
also accepts regular expressions.
JAVASCRIPT
const newString = 'Hello World and outer World!'.replace(/ World/g, '')console.log(newString) // 'Hello and outer!'
In the regular expression, we can pass in the word as is, including any special characters like a space. The g
means global search, i.e. watch out for multiple occurrences.
What if the words have different cases? Simply add an i
after g
, and the search won't be case-sensitive.