Remove Specific Substring from a String in JavaScript



We are given a main string and a substring, our job is to create a function, let’s say removeString() that takes in these two arguments and returns a version of the main string which is free of the substring.

Here, we need to remove the separator from a string, for example −

this-is-a-sting

Let’s now write the code for this function −

const removeString = (string, separator) => {
   //we split the string and make it free of separator
   const separatedArray = string.split(separator);
   //we join the separatedArray with empty string
   const separatedString = separatedArray.join("");
   return separatedString;
}
const str = removeString('this-is-a-sting', '-');
console.log(str);

The output of this code in the console will be −

thisisastring
Updated on: 2020-10-09T11:51:00+05:30

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements