Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace number in a string using regex or something else

I am not so good with regex. I am struggling to find a solution for a small functionality.

I have a ajax response which returns a string like "Your ticket has been successfully logged. Please follow the link to view details 123432."

All I have to do is replace that number 123432 with <a href="blablabla.com?ticket=123432"> using javascript.

like image 710
Krishna Avatar asked Apr 20 '10 18:04

Krishna


People also ask

How do I replace a number in a string?

To replace all numbers in a string, call the replace() method, passing it a regular expression that globally matches all numbers as the first parameter and the replacement string as the second. The replace method will return a new string with all matches replaced by the provided replacement.

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.

Does string replace use regex?

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


2 Answers

Try this:

fixedString = yourString.replace(/(\d+)/g, 
    "<a href='blablabla.com?ticket=$1\'>$1</a>");

This will give you a new string that looks like this:

Your ticket has been successfully logged. Please follow the link to view details <a href='blablabla.com?ticket=123432'>123432</a>.

like image 193
Andrew Hare Avatar answered Oct 15 '22 10:10

Andrew Hare


var str = "Your ticket has been successfully logged. Please follow the link to view details 123432.";
str = str.replace(/\s+(\d+)\.$/g, '<a href="blablabla.com?ticket=$1">$&</a>');

this code will output

<a href="blablabla.com?ticket=123432">Your ticket has been successfully logged. Please follow the link to view details 123432.</a>
like image 42
vooD Avatar answered Oct 15 '22 11:10

vooD