views:

60

answers:

2

Hi,

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.

+3  A: 

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>.

Andrew Hare
Notice that the replacement text is not constant.
Mark Byers
Shouldn't that be fixedString = yourString.replace(/(\d+)/g, "<a href='blablabla.com?ticket=$1\'>$1</a>");
Chad
@Chad - Yes it should - nice call :)
Andrew Hare
Awesome, it worked for me. You saved my day.
Krishna
A: 
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>
vooD