Last updated on Nov 14, 2020 by Suraj Sharma
In this tutorial, you will learn how you can remove a particular substring from a JavaScript string.
The replace() method takes two parameters, first one is the substring to replace and the second parameter is the string to replace with.
To remove the substring, we pass an empty string to the second parameter.
Example:
const newString = 'Hello world'.replace('o', '');
console.log(newString); // 'Hell wrld'
console.log('Hello world'.replace('ll', '')); // 'Heo world'
We are going to pass the substring to remove as a parameter to the split()
method.
The split()
method returns an array of substrings separated by the substring passed as an argument.
Next, join the array using an empty string to get back a string with the substring removed
Example
const substrings = 'Hello World'.split('Wo'); // ['Hello ', 'rld']
console.log(substrings.join('')) // 'Hello rld';
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.