Enzio Pixel Enzio Pixel - 1 year ago 64
jQuery Question

Loop through numbers in a string (numbers only)

I'm trying to highlight the 4th, 5th and 6th number of a string by wrapping a

tag around it. The string contains numbers, commas, a dollar sign and occasionally dots.

Here's my string:


I want the output exactly the same, except the 4th, 5th and 6th number are wrapped inside
tags. I've tried using looping through the string using a
loop. However, I don't want the any other character to influence the count (only the numbers in the string).


Let's say the string would be different, I still want to have the 4th, 5th and 6th number wrapped in a

"$61,0<span>0</span><span>2</span>.<span>1</span>2" == "$61,002.12"

How can I achieve this with Javascript / jQuery?

Answer Source

I would use a regex with a replacement function, where depending on the "index" of the digit, it get's wrapped in <span> tags.

$("div").html(function(_, old) {
  var i = 0;
  return old.replace(/\d/g, function(num) {
    return i >= 4 && i <= 6 ? "<span>" + num + "</span>" : num;
span { font-weight: bold }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download