我正在尝试将字符串中的网址转换为链接,其条件是网址必须与我正在使用的网址相同。我该怎么做?
str = "This is a www.domain.com text with url. This is another url: www.domain2.com. This is a part of a url: http://domain.com/foo.php. This is another link: https://stackoverflow.com/questions/ask. Another link: domain.com/bar.php";
我想要的是:
<a href='www.domain.com'>domain.com</a>
<a href='http://domain.com/foo.php'>/foo.php</a>
。<a href='domain.com/bar.php'>/bar.php</a>
如何使用javascript执行此操作?
答案 0 :(得分:2)
应该这样做:
str.replace(/(?:(?:http:\/\/)?(?:www\.)?(domain\.com))(\/[a-zA-Z]+\.php)?/g,
function(a,b,c) {
return '<a href="'+a+'">'+(c ? c : b)+'</a>';
});
这是工作小提琴http://jsfiddle.net/URLzx/1/。