eric.dummy
eric.dummy

Reputation: 399

Apply color to only part of an array?

I'm going to reproduce an array from other question for this:

console.log(arrayStr);

which outputs:

(a) - text1, (b) - text2, (c) - text3, (d) - text3

How can I apply a color to (a) (b), etc. parts?

The regex would be: /\([^)]+\)/g;

Thanks.

Upvotes: 1

Views: 37

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can expand your regex to capture a group. You can then use that to wrap the matched (X) values in span elements to which you can apply some CSS. Try this:

$('div').html(function(i, html) {
  return html.replace(/(\([^)]+\))/g, "<span>$1</span>");
})
span { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>(a) - text1, (b) - text2, (c) - text3, (d) - text3</div>

Here's a native JS implementation:

var el = document.getElementById('foo');
el.innerHTML = el.innerHTML.replace(/(\([^)]+\))/g, "<span>$1</span>");
span { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">(a) - text1, (b) - text2, (c) - text3, (d) - text3</div>

Upvotes: 2

Related Questions