Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 472
Burning Crystals Avatar asked May 23 '15 03:05

Burning Crystals


People also ask

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

What is replace () in JavaScript?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.


1 Answers

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

like image 97
bugwheels94 Avatar answered Sep 20 '22 20:09

bugwheels94