0

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]
'cats'

How would I go about getting:

> modified_string
'bears and and dogs'

Thanks

Edit:

> original_string = "bears and cats and dogs"
'bears and cats and dogs'
> original_string.replace(/cats/, "")
'bears and  and dogs'

But is there another way? I'm coming from ruby so there's always a snappy method for everything

mbigras
  • 7,664
  • 11
  • 50
  • 111
  • This is answered in http://stackoverflow.com/questions/10398931/javascript-how-to-remove-text-from-a-string . – RajeshM Jul 04 '16 at 00:15

1 Answers1

0

Method 1: Use .replace()

var original_string = "bears and cats and dogs";

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

console.log(modified_string);

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
  .split(/\s/)
  .filter(function(word) {
    return (word !== 'cats')
  })
  .join(' ');

console.log(modified_string);

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);
}

console.log(modified_string);
KevBot
  • 17,900
  • 5
  • 50
  • 68