If I have a block of text inside a div like:
<div id='t1'>
This is a great testing string. Tomorrow grass is green.
</div>
我想将所有字母"g"替换为指向google的链接,例如
<a href='www.google.com'>g</a>
是否可能只用Javascript/jquery来完成这个操作?
If I have a block of text inside a div like:
<div id='t1'>
This is a great testing string. Tomorrow grass is green.
</div>
我想将所有字母"g"替换为指向google的链接,例如
<a href='www.google.com'>g</a>
是否可能只用Javascript/jquery来完成这个操作?
如果您想执行简单的字符串替换,可以使用以下方法:
var div = document.getElementById("t1");
div.innerHTML = div.innerHTML.replace(/g/g, "<a href='http://www.google.com'>g</a>");
var div = document.getElementById("t1");
var mapper = {
g: "http://www.google.com",
G: "http://stackoverflow.com"
};
div.innerHTML = div.innerHTML.replace(/[Gg]/g, function(fullmatch){
return "<a href='" + mapper[fullmatch] + "'>" + fullmatch + "</a>";
});
var t1 = document.getElementById('t1')
t1.innerHTML = t1.innerHTML.replace(/g/g, '<a href="http://www.google.com/">g</a>')
/g/g
中,第一个g
代表您要搜索的内容。第二个g
表示全局(即替换所有)。$('#t1').html( $('#t1').text().replace(/g/g,"<a href='www.google.com'>g</a>") );
text
而不是其他html
单词。优点是>
不会被替换破坏。它将被视为>
并在最终结果中仍然起作用。这是我和Rob的解决方案所缺乏的东西。可能存在的危险缺点是<span onmouseover="...">
有可能引入XSS漏洞,因为生成的文本将被重新设置为HTML <span onmouseover="...">
。因此,只有在已知原始输入是安全的情况下才应使用此代码。 - 700 Software
\.
, 因为.
匹配除换行符外的所有字符(在正则表达式中,句点具有特殊意义)。 - Rob W/word/g
是一个正则表达式,用于匹配 "word
"。/g
告诉replace
函数继续匹配,直到找不到匹配项(默认行为是在第一次匹配时停止)。 - Rob W/g
的理解是错误的!非常感谢你。 - Isuru