【发布时间】:2012-08-06 20:44:54
【问题描述】:
我正在通过 getJSON 提取推文并使用 javascript 将它们写入 Google 地图信息窗口。问题是,这些推文带有文本链接,但没有格式(也没有 ids/classes/任何可以缩小查找和替换的内容)。这是我现在用来查找文本的代码混搭,但我无法将它在<a> 标签中找到的任何内容包装起来以正确显示链接:
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
var jthis = $(this);
$("*").each(function () {
if (jthis.children().length == 0) {
jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
我是否忽略了某些事情,或者有人知道更好的方法吗?
【问题讨论】:
-
如果你不想使用 jQuery,这很好用:gist.github.com/ryansmith94/0fb9f6042c1e0af0d74f
标签: javascript jquery regex replace