如何在jQuery中替换任意字符串?
假设我有一个字符串"-9o0-9909"
,我想用另一个字符串来替换它。
如何在jQuery中替换任意字符串?
假设我有一个字符串"-9o0-9909"
,我想用另一个字符串来替换它。
您可以使用以下代码来替换页面正文中第一次出现的单词:
var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);
如果你想要替换一个词的所有出现,那么你需要使用正则表达式,并声明它是全局匹配 /g
:
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
如果您想要一行代码:
$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));
你基本上是将页面在<body>
标签内的所有HTML内容存储为一个字符串变量,使用replace()函数找到并更改第一次出现的字符串为新的字符串。如果你想查找和替换所有出现的字符串,那么可以加入一点正则表达式。
请点击此处查看演示 - 查看左上角的HTML文本来查看原始文本、下方的jQuery代码以及右下方的输出结果。
像其他帖子中提到的那样,替换整个 HTML 的做法是不好的,因为它会重新插入整个DOM,并有可能破坏作用于这些元素的任何其他javascript。
相反,使用jQuery过滤器仅替换页面上的文本而不是DOM元素本身:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('-9o0-9909','The new string');
});
this.nodeType 是我们要替换内容的节点类型。nodeType 3 表示文本。在此处查看完整列表。
我有一个字符串“-9o0-9909”,我想用另一个字符串替换它。
下面的代码可以做到这一点。
var str = '-9o0-9909';
str = 'new string';
开玩笑的,使用JavaScript替换文本节点并不是一件容易的事情。
我写了一篇关于此的文章:使用JavaScript替换文本。
<br />
(child 为 null)时会出现故障,并且有时会因 "split offset exceeds text node length" 而无法解释地崩溃。另外,“canvas” 被拼错为“cavas”。尽管如此,还是点赞。 - bishop使用html替换的想法不错,但如果应用到document.body上,页面会闪烁且广告将消失。
我的解决方案:
$("*:contains('purrfect')").each(function() {
var replaced = $(this).html().replace(/purrfect/g, "purrfect");
$(this).html(replaced);
});
$("#elementID").html("another string");
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
对于变量:
var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);
<div id="content">
内的文本替换为tel:
方案链接。findAndReplaceDOMText(document.getElementById('content'), {
find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
replace:function (portion) {
var a = document.createElement('a');
a.className = 'telephone';
a.href = 'tel:' + portion.text.replace(/\D/g, '');
a.textContent = portion.text;
return a;
}
});