使用正则表达式或其他替换字符串中的数字

时间:2022-05-11 10:25:19

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

我有一个ajax响应,返回一个字符串,如“您的票证已成功登录。请按照链接查看详细信息123432”。

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

我所要做的就是用使用javascript替换这个号码123432。

2 个解决方案

#1


17  

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

您的机票已成功登录。请点击链接查看 123432 的详细信息。

#2


1  

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>

#1


17  

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

您的机票已成功登录。请点击链接查看 123432 的详细信息。

#2


1  

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>