mbigras mbigras - 1 year ago 39
Javascript Question

How do I extract a substring and subtract it from the original string in javascript?

I know that:

> original_string = "bears and cats and dogs"
'bears and cats and dogs'
> useful_array = original_string.match(/cats/)
[ 'cats', index: 10, input: 'bears and cats and dogs' ]
> sub_string = useful_array[0]

How would I go about getting:

> modified_string
'bears and and dogs'


Answer Source

Method 1: Use .replace()

var original_string = "bears and cats and dogs";

var modified_string  = original_string.replace('cats ', '');


Strings have a method called replace which accepts a variety of parameters including regex, strings, and of course modifiers (g,i, etc).

So just using the replace on the string to replace cats with '' will do what you are looking for.

Method 2: Use an array and filter out what you don't want

After your edit to the question, another, more complex way to do this would be to split the string into an array and filter out the word cats. Then rejoin the array into a string by a space.

var original_string = "bears and cats and dogs";
var modified_string = original_string
  .filter(function(word) {
    return (word !== 'cats')
  .join(' ');


Method 3: Remove by getting index of substring, then slice

And of course, if you want to approach it in the way it looks like you were, via indexes on the string, you can do it like this:

var original_string = "bears and cats and dogs";
var wordToReplace = 'cats ';

var index = original_string.indexOf(wordToReplace);
var modified_string = '';

if (index > -1) {
  modified_string = original_string.slice(0, index) + original_string.slice(index + wordToReplace.length);