Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex - Insert word (hit)

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

like image 823
Peter Avatar asked Mar 02 '26 21:03

Peter


1 Answers

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';
like image 68
Kobi Avatar answered Mar 05 '26 10:03

Kobi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!