javascript JQuery 如何替换文本区域内的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11581372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:44:22  来源:igfitidea点击:

JQuery How to replace strings inside a textarea?

javascriptjqueryhtmlregexreplace

提问by Harry

Current Textarea:

当前文本区域:

<textarea id="event_content">
This text area could be full of information..www.london2012.com
And might contain upto 5 links that all need updating.
www.rio2016.org

Link already converted. this should be left.
<a href="http://www.thetimes.co.uk" target="_blank">www.thetimes.co.uk</a>
</textarea>


Desired Textarea after jquery: all links to be cleaned/replaced with tags and target attr

jquery 后所需的文本区域:所有链接都将被清理/替换为标签和目标属性

<textarea id="event_content">
This text area could be full of information
<a href="http://www.london2012.com" target="_blank">www.london2012.com</a>
And might contain upto 5 links that all need updating.
<a href="http://www.rio2016.org" target="_blank">www.rio2016.org</a>

Link already converted. this should be left.
<a href="http://www.thetimes.co.uk" target="_blank">www.thetimes.co.uk</a>
</textarea>


21 July 2012 - ?mega'scode worked a treat thanks, but could be improved by leaving already converted links?

2012 年 7 月 21 日 - ?mega 的代码效果很好,谢谢,但可以通过保留已转换的链接来改进?

回答by ?mega

I believe you are looking for something like this (click hereto test this fiddle):

我相信你正在寻找这样的东西(点击这里测试这个小提琴):

$('#event_content').val(
  $('#event_content').val().replace(/\b(http(s|):\/\/|)(www\.\S+)/ig,
    "<a href='http$2://$3' target='_blank'>$3</a>"));

回答by Wouter Janssens

var link = $("#event_content");
var text = link.html();
var linktext = '<a href="' + text + '" target="_blank">' + text + '</a>'
link.html(linktext);

回答by XCS

$(function(){
    var old = $('#event_content').val();

    var news = '<a href="http://'+old+'" target="_blank">'+old+'</a>';

    $('#event_content').val(news);
});

Note that the <a>will not be displayed in textarea, but instead plain text will be shown.

请注意,<a>将不会显示在 textarea 中,而是显示纯文本。

Demo: http://jsfiddle.net/3xEh2/1/

演示:http: //jsfiddle.net/3xEh2/1/

回答by Mark K

fiddle

小提琴

This will replace all the links and leave the other text there as well.

这将替换所有链接并保留其他文本。

$(function(){
var old = $('#event_content').val();
var news = old.replace("www.london2012.com", '<a href="http://www.rio2016.com" target="_blank">www.rio2016.com</a>');   
$('#event_content').val(news);
});