Steve
Steve

Reputation: 4898

Replacing an entire sentence when a phrase is found

I'm looking for a JavaScript regular expression that will look in a sentence for a phrase, like "seem to be new" and if it finds that phase it replaces the entire sentence with "seem". So all the sentences below would be replaced by "seem"

How do I get rid of the "You seem to be new" message?
How do I get kill the "You seem to be new" message?
How do I stop the "You seem to be new" message from appearing?

Upvotes: 1

Views: 2313

Answers (3)

Jeroen Ingelbrecht
Jeroen Ingelbrecht

Reputation: 808

You can use the String.replace function like so:

var newString = (
            'How do I get rid of the "You seem to be new" message?'
          + ' How do I get kill the "You seem to be new" message?'
          + ' How do I stop the "You seem to be new" message from appearing?'
    ).replace(/You seem to be new/g, "seem");

jsFiddle

Upvotes: 1

Smern
Smern

Reputation: 19066

Is this what you are looking for?

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); // "seemseemseem"

Fiddle

Also, so you can see what happens if I throw in a string that doesn't match:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); //seemseem This sentence doesn't seem to contain your phrase.seem

Fiddle

If you want to replace the sentence but keep the same punctuation:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*([?!.])/g," seem$1");
console.log(str); // seem? seem? This sentence doesn't seem to contain your phrase. seem?

Fiddle

Upvotes: 1

vol7ron
vol7ron

Reputation: 42089

An alternative to using regexp is to use indexOf

Fiddle

var str = 'How do I get rid of the "You seem to be new" message?\n\
How do I get kill the "You seem to be new" message?\n\
How do I stop the "You seem to be new" message from appearing?';

var lines          = str.split('\n')  ,
    search_string  = 'seem to be new' ,
    replace_string = 'seem'           ;

for ( var i=0,n=lines.length; i<n; i++ )
   if ( lines[i].indexOf(search_string) > -1 )
      lines[i] = replace_string ;

alert('original message: \n' + str + '\n\nnew message: \n' + lines.join('\n'));

Upvotes: 1

Related Questions