Reputation: 4898
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
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");
Upvotes: 1
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"
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
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?
Upvotes: 1
Reputation: 42089
An alternative to using regexp is to use indexOf
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