如何将字符串中的锚标记替换为仅作为文本的链接。
实际值:
var text = "This is a test article with links which need to be replaced. < a href=" http://local.mysite.com/test/f/english-as-a-second/p/addpost">local.mysite.com/.../addpost< /a> Another link which needs to be replaced < a href=" http://local.mysite.com/test/f/match">local.mysite.com/.../match < /a>"
期望的结果:
This is a test article with links which need to be replaced. http: //local.mysite.com/test/f/english-as-a-second/p/addpost
需要更换的另一个链接http://local.mysite.com/test/f/match
答案 0 :(得分:0)
假设您被允许使用jQuery,这可以。
var str = 'This is a test article with links which need to be replaced. <a href=" http://local.mysite.com/test/f/english-as-a-second/p/addpost">local.mysite.com/.../addpost</a> Another link which needs to be replaced <a href=" http://local.mysite.com/test/f/match">local.mysite.com/.../match </a>';
var $str = $('<div/>').html(str);
$str.find('a').each(function ()
{
$(this).replaceWith($(this).attr('href'));
});
var result = $str.text();
console.log(result);
特别提示:请注意<
和a
之间的空格。您< a
并不总是被识别为正确的html。 < /a
中也是如此。