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:
$&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):Note that you probably want the
gflag 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: