是的,使用String.replace(regex,replaceString)来做到这一点。
下面是一个例子:
var text = "You should visit StackOverflow. I found it on Wikipedia.";
var newText=text.replace(/stackoverflow/gi,
"<a href='http://www.stackoverflow.com/'>StackOverflow</a>");
的g
代表全球性的,所以它将替换所有实例和i
指不区分大小写的搜索。
如果您要更换的常用词,如“字典”链接到dictionary.com
它会更好,如果你只是换掉它,如果你的用户增加了一个特殊的标记,例如:
"You should visit StackOverflow. I found it on Wikipedia."
不应该可以用链接替代,除非它是这样写的:
"You should visit &StackOverflow. I found it on Wikipedia."
那么你的方法将只需要添加特殊符号。
另外,我想拥有的数据在一个这样的数组:
var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];
然后创建一个循环来查找和替换的实例:
function addLinks(textInput) {
for (var i=0; i<linkArray.length; i++) {
textInput = addLink(textInput, linkArray[i]);
}
return textInput;
}
function addLink(textInput, link) {
var replaceString = "<a href=\"" + link[1] + "\" title=\""
+ link[2] + "\">"
+ link[0] + "</a>";
return textInput.replace(new RegExp("&"+link[0], "gi"), replaceString);
}
你预先处理文本你把之前在DOM,或添加这些链接,一旦文本alreadyh在DOM? – 2012-04-25 16:51:27
这不是简单地用其他词替换单词吗? http://www.w3schools.com/jsref/jsref_replace.asp – DanRedux 2012-04-25 16:51:29
有一个很像你的已经在StackOverflow上semilar问题:http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery – YMMD 2012-04-25 16:52:01