1

I have been searching SO to find the correct way to use a var as part of a regex . The idea is to get each of the searchable fields on the page and check if the text contains the search term, then if so, replace that portion of the text and wrap it in a styled span. this is the part of the code which is not working correctly, "/\\"+src+"/gi",

$('.srch').each(function () {

        var txt = $(this).text(),
            src = $('#Srch_Srch_txt').val();

        var s = txt.replace("/\\"+src+"/gi", '<span class=highlight>' + src + '</span>');

        $(this).html(s);

    })

Thank you in advance, Will.

wf4
  • 3,727
  • 2
  • 34
  • 45

1 Answers1

1

You can construct a dynamic regex doing string manipulation using Javascript's RegExp object

var re = new RegExp("ab" + src, "i"); // assuming src is a string variable
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • A little confusing but I managed to get it working from your example... `var re = new RegExp( src, "gi"); var s = txt.replace(re, '' + src + '');` worked for me. – wf4 Oct 16 '13 at 15:54