Burning Crystals
Burning Crystals

Reputation: 1167

replacing numbers in a string with regex in javascript

I have string that contains numbers and characters. I want to replace the numbers with another value that will give it a css class of someClass.

Now I got the code to detect all the numbers in the string and replace it with something else.

My question is how do I get the current number match and put it to the new string or value that will replace the original one?

Basically what I want to happen is:

for example, I have this string: 1dog3cat, I want it to get replaced with <span class="someClass">1</span>dog<span class="someClass">3</span>cat

Here's my current code:

    var string_variable;
    string_variable = "1FOO5,200BAR";
    string_variable = string_variable.replace(/(?:\d*\.)?\d+/g, "<span class='someClass'>" + string_variable + "</span>");
    alert(string_variable);

Upvotes: 5

Views: 416

Answers (1)

bugwheels94
bugwheels94

Reputation: 31950

Simply remember the matched pattern using parenthesis and retrieve that value using $1 and add span tag to it.

Use this regex

string_variable = string_variable.replace(/(\d+)/g, "<span class='someClass'>$1</span>");

See DEMO

Upvotes: 7

Related Questions