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);
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With