Javascript 将#关键字from替换为指定<;部门></部门>;使用Jquery
我无法从输入字符串中替换关键字 我有Javascript 将#关键字from替换为指定<;部门></部门>;使用Jquery,javascript,jquery,Javascript,Jquery,我无法从输入字符串中替换关键字 我有 <div id="Wrap"> <span class="common"><div id="main0"> to test it #sky </div></span> </div> 为了测试它#天空 我想这样: <div id="Wrap"> <span class="common"> <div id="main0"> to test <a
<div id="Wrap">
<span class="common"><div id="main0"> to test it #sky </div></span>
</div>
为了测试它#天空
我想这样:
<div id="Wrap">
<span class="common">
<div id="main0"> to test <a href="http://mysite.com/search?q=#sky">#sky</a> </div>
</span>
</div>
检验
我尝试在jquery中使用replace,但没有得到。。。
我正在用jquery或javascript寻找解决方案
请帮助我…类似于:
$('#main0').html($('#main0').html().replace(/(#\w+)/g, '<a href="http://mysite.com/search?q=$1">$1</a>'));
$('main0').html($('main0').html().replace(/('main0'));
使用正则表达式(顺便说一句,这只是一个普通的JS函数),该正则表达式匹配#
和单词字符$1
是对第一个捕获组()
内容的反向引用
您可以通过一些警告快速轻松地完成此操作
$('#element').html(function(i, html) {
return html.replace(/#\w+/g, '<a href="http://mysite.com/search?q=$&">$&</a>';
});
确保在表达式上使用
/g
开关,例如:
var match = /(#\w+)/g;
var text = $("#main0").text();
var result = text.replace(match, "<a href=\"http://mysite.com/search?q=$1\">$1</a>");
$("#main0").text(result);
var-match=/(#\w+)/g;
var text=$(“#main0”).text();
var result=text.replace(匹配“”);
$(“#main0”).text(结果);
/g
开关确保替换所有匹配项,而不仅仅是第一个匹配项。U应将此问题标记为已回答的问题,每个答案的左侧都有一个箭头标记。
var match = /(#\w+)/g;
var text = $("#main0").text();
var result = text.replace(match, "<a href=\"http://mysite.com/search?q=$1\">$1</a>");
$("#main0").text(result);