jQuery在textarea中用href url替换anchor标签

时间:2017-01-12 02:32:33

标签: jquery anchor

如何将字符串中的锚标记替换为仅作为文本的链接。

实际值:

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

1 个答案:

答案 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中也是如此。