首页 > 解决方案 > 如何使用正则表达式动态地对字符串应用替换 JAVASCRIPT?

问题描述

我有这个字符串和这个正则表达式。它匹配超链接仅供参考。

var str = "string https://www.pleasehelpme.com string";
var expr = "^(https:|http:|www\.)\S*";
var regex = new RegExp( expr  );

如果我想用常量字符串替换 Url,我应该这样做:

var myconstantstring = "https://www.thxforyourhelpcommunity.com"
var replaced = str.replace(regex, myconstantstring);
console.log(replaced);
// displays "string https://www.thxforyourhelpcommunity.com string"

但我想用相同的 url 替换字符串中的 url,用 HTML 标签包围,所以结果如下:

"string <a href='https://www.thxforyourhelpcommunity.com'>clic here </a> string"

有没有办法通过返回匹配表并将其直接替换到字符串中来做到这一点?显然,我可以通过将过程与多个小步骤分开来实现这一点,但这不是我想要的。

谢谢你们。

标签: javascripthtmlregexreplacetags

解决方案


推荐阅读