Bill Warren
Bill Warren

Reputation: 392

Jquery - Regex to change color of Unicode characters in text?

We have this... the simple version... In the live version, "this" is inside of two jQuery each loops as we are searching multiple divisions for multiple unicode characters...

 <p id="searchDiv1">Root Juice&#8482;</p>

and we want to change the color of the "™" to red.. so we have this...

var char = '&#8482;';
var thisDiv = '#searchDiv1';

var replaceWithThis = '<span color="red">'+char+'</span>';
var newText = $(thisDiv).html().replace( /[char]/g, replaceWithThis);
$( thisDiv ).html(newText);

Unfortunately... the results look like this..

Root Jui™e™

Obviously... we need better regex... or something... Anybody got any clues? Thanks...

Upvotes: 0

Views: 1546

Answers (1)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201568

There are several issues with the code. Here is a minimally modified version that works:

var char = '\u2122';
var thisDiv = '#searchDiv1';
var replaceWithThis = '<font color="red">'+char+'</font>';
var newText = $(thisDiv).html().replace(new RegExp(char, 'g'), replaceWithThis);
$( thisDiv ).html(newText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="searchDiv1">Root Juice&#8482;</p>

First, you can’t use &#8482; in JavaScript, unless you make JavaScript parse it as HTML. Use the JavaScript character escape \u2122 instead. Here 2122 is the hexadecimal form of decimal 8482.

Second, when you use [char] in a regexp, it is taken literally: it matches any of the characters c, h, a, r. No variable substitution takes place here. Use the RegExp constructor to build a regexp from the value of a variable.

Third, span elements do not have a color attribute. Use the font element instead. (It works just fine, even though many people frown upon it and curse it.) Alternatively, use e.g. a span element with a class attribute and define a CSS rule using that class. Or use inline CSS, <span style="color: red">.

Upvotes: 1

Related Questions