Replacing numbers in a string with regular expression in javascript

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

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

My question is how to get the current number to match and put it on a new line or a value that will replace the original?

Basically, I want this to happen:

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

Here is 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); 
+5
source share
1 answer

Just remember the matching pattern with a bracket and extract that value with $1 and add a span tag to it.

Use this regex

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

See DEMO

+6
source

All Articles