javascript - 如何使用正则表达式动态地对字符串应用替换 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"
有没有办法通过返回匹配表并将其直接替换到字符串中来做到这一点?显然,我可以通过将过程与多个小步骤分开来实现这一点,但这不是我想要的。
谢谢你们。
解决方案
推荐阅读
- python - SyntaxError: 无效的语法 - len(targets)
- javascript - 返回具有特定键的对象:嵌套在另一个数组中的数组中的值对 - Javascript
- scala - 将 String 转换为类型列 Spark
- c - 操作长字符串时内存损坏
- http - 如何在颤动中解析字符串数组?
- c++ - 默认在索引数组的第一个位置设置值
- powershell - MSOnline 无法加载类型“System.IdentityModel.Tokens.JwtSecurityToken”
- docker - 将开发环境从一台 EC2 机器复制到另一台机器
- javascript - 将 Javascript 数组添加到编号列表
- html - 如何在不播放视频的情况下显示 html5 视频总时长