Username_null
Username_null

Reputation: 1315

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.

Upvotes: 3

Views: 3184

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can achieve this by using Capturing Groups in your regex. This will maintain the case of the matched string when creating the output. Here's a working example:

const input = "SENSasianAL";
const output = input.replace(/(S)(ASIAN)(A)/ig, "$1<em>$2</em>$3");

console.log(output);

Upvotes: 5

Microfed
Microfed

Reputation: 2890

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

For additional unformation about regexp see this page.

Upvotes: 2

Gijs
Gijs

Reputation: 5262

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.

Upvotes: 9

Related Questions