Javascript将字符串与模式匹配,并在匹配的字符串中插入一些文本

Javascript将字符串与模式匹配,并在匹配的字符串中插入一些文本,javascript,regex,Javascript,Regex,输入: 废话废话文本废话随机 操作:匹配具有相对链接的href标记的所有实例,然后插入主机url。 输出: 废话废话文本废话随机 我想知道如何在javascript中快速、干净地完成这项工作,需要正则表达式专家的帮助。非常感谢您的输入 这个基于正则表达式的解决方案应该适合您: blah blah blah text blah <a href="http://www.rooturl.com/abcblah/blah">some random text</a> text

输入:

废话废话文本废话随机
操作:匹配具有相对链接的href标记的所有实例,然后插入主机url。 输出:

废话废话文本废话随机

我想知道如何在javascript中快速、干净地完成这项工作,需要正则表达式专家的帮助。非常感谢您的输入

这个基于正则表达式的解决方案应该适合您:

blah blah blah text blah <a href="http://www.rooturl.com/abcblah/blah">some random text</a> text blah blah random
str='blah blah text blah text blah random';
repl=str.replace(/(href=['”](?!https?:)\/?/g,“$1http://www.rooturl.com/");
console.log(repl);

现场演示:您能展示一下您的尝试吗?您能详细说明一下为什么要这样做吗?如果您访问锚定dom元素href attributes,无论发生什么情况,它都会以主机名返回。@nanshi为什么您认为您必须这样做?您的最终目标是什么?@raam86,html现在不仅仅适用于web,您可以在ios或android上的网络控制中打开它以o、 当您遇到相对链接时,基本上是死链接。非常感谢您的帮助。更新版本:rep=str.replace(/(href=['”)(?!((https?:)|(mailto:)|(tel:)))))/g,“$1”+主机名);--结果证明这很复杂,我担心我可能会错过一些有效的标记:)我的最终版本:rep=str.replace(/(href=['“])(\/)/g,“$1”+主机名+“$2”)--到目前为止,我还没有弄清楚我可能会错过什么。
blah blah blah text blah <a href="http://www.rooturl.com/abcblah/blah">some random text</a> text blah blah random
str = 'blah blah text blah <a href="/abcblah/blah">some random text</a> text blah random';
repl = str.replace(/(href=['"](?!https?:))\/?/g, "$1http://www.rooturl.com/");
console.log(repl);