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

时间:2013-07-10 17:34:08

标签: javascript regex

输入:

 blah blah blah text blah <a href="/abcblah/blah">some random text</a> text blah blah random

操作:匹配具有相对链接的href标记的所有实例,然后插入主机网址。 输出:

blah blah blah text blah <a href="http://www.rooturl.com/abcblah/blah">some random text</a> text blah blah random

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

1 个答案:

答案 0 :(得分:2)

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

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);

现场演示:http://ideone.com/G5F0vF

相关问题