How to remove a particular substring from a string in javascript

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.


Two ways to remove a substring from a JavaScript string



1. Using String.replace() method


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'


2. Using String.split() method


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.