is it possible to insert the word that was found into the replace ?
$(function() {
content = 'hallo mein name ist peter und ich komme aus berlin. Und du?';
words = 'mein na,berlin'
words = words.replace(/,/,'\|');
words = words.replace(/\s/,'\\s');
regex = new RegExp(words,'gi');
content = content.replace(regex,'<strong>*insert here the word that was found*</strong>');
alert(''+content+'');
});
working example http://www.jsfiddle.net/V9Euk/227/
Thanks in advance! Peter
Try this:
content.replace(regex,'<strong>$&</strong>');
$& is replaced with the full match.
Working example: http://www.jsfiddle.net/V9Euk/228/
If you are more comfortable with it, you can add a group and replace it with $1 (this one will raise less questions):
words = words.replace(/,/g,'\|');
words = words.replace(/\s/g,'\\s');
words = '(' + words + ')';
regex = new RegExp(words, 'gi');
content = content.replace(regex,'<strong>$1</strong>');
Note that you probably want the g flag on these replaces, or you only change the first space and comma.
If you also want to avoid partial matching (so "mein na" doesn't capture), add \b:
words = '\\b(' + words + ')\\b';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With