jqueryregexcase-sensitive

Jquery replace text but keep case


I am building a website for someone who likes to use the word "Sensasianal" to describe his asian cuisine. The word asian is always picked out using another color which I managed to achieve in Jquery using .replace(), thus:-

replaceAsian.html(replaceAsian.html().replace(/sasiana/ig, "s<em>asian</em>a"));

I can then style the element with a separate color.

However if the original text is uppercase the result is mixed-case.

So I tried this

replaceAsian.html(replaceAsian.html().replace(/SASIANA/ig, "S<em>ASIAN</em>A"));
replaceAsian.html(replaceAsian.html().replace(/sasiana/ig, "s<em>asian</em>a"));

But the result is still mixed-case.

If someone could advise me on how to make the change to the text but retain the original case I would appreciate the assist. Many thanks.


Solution

  • replaceAsian.html(replaceAsian.html().replace(/(s)(asian)(a)/ig, "$1<em>$2</em>$3"));
    

    will preserve case, because it reuses the matched text.

    Note that i is the case insensitivity flag, and g means it will match every occurrence, rather than just the first as would happen without the g flag.

    For a pretty good overview of regular expression functionality in JS, see MDN.