5

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);

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

used this answer. thanks @Ankit, going to accept this answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.