OneBite.Dev - Coding blog in a bite size

remove a substring from a string in Javascript

Code snippet on how to remove a substring from a string in Javascript

  const inputString = "This is a sample string";
  const substringToRemove = "sample";
  const outputString = inputString.replace(substringToRemove, ''); 
  console.log(outputString);

The code above will remove the substring ‘sample’ from a string. The first line defines a variable called inputString that holds the string where we want to remove the substring from. The second line defines a variable called substringToRemove that holds the string we want to remove. The third line uses the replace method on the inputString variable, which replaces the substringToRemove with an empty string. Finally, the fourth line logs the modified string to the console. The outputString variable holds the modified string.

javascript