2017-01-12 6 views
-1

文字列内のアンカータグをテキストとしてリンクのみで置き換える方法を教えてください。jQueryは、アンカータグをテキストエリアのhref urlに置き換えます。

実際:

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

と仮定すると、あなたは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にも同じことがあります。

+0

ありがとうございました! – user3565199

+0

NP。私は人がテキスト領域にコピー/貼り付けをしていた場所で、貼り付けられたデータにhtmlコードを持っている人に対処する必要があったのと同じようなことを最近行った。このトリックはとても便利でした。 – nurdyguy

関連する問題