javascript Jquery 替换每个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11336207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery replace for each
提问by user1299846
I want to replace every "New" inside every link with span tag.
我想用 span 标签替换每个链接中的每个“新”。
Is it right?
这样对吗?
$("a:contains('New')").each(function () {
$(this).html($(this).html().replace("New", "<span class='new'>New</span>"));
});
采纳答案by graygilmore
Here's a pretty simple method as well:
这里还有一个非常简单的方法:
$("a:contains('New')").each(function() {
$(this).html(function(index, text) {
return text.replace('New', '<span class="new">New</span>');
});
});
From here: JavaScript/jQuery: replace part of string?
从这里开始:JavaScript/jQuery:替换字符串的一部分?
Edit:
编辑:
Ricardo Lohmann's answer is better, kills the each() function:
Ricardo Lohmann的回答更好,杀死了 each() 函数:
$("a:contains('New')").html(function(i, text) {
return text.replace(/New/g, '<span class="new">New</span>');
});
回答by Tats_innit
Regex : Working Demohttp://jsfiddle.net/WujTJ/
正则表达式:工作演示http://jsfiddle.net/WujTJ/
g = /g modifier makes sure that all occurrences of "replacement"
g = /g 修饰符确保所有出现的“替换”
i - /i makes the regex match case insensitive.
i - /i 使正则表达式匹配不区分大小写。
A good read:if you keen: http://www.regular-expressions.info/javascript.html
一个很好的阅读:如果你热衷:http: //www.regular-expressions.info/javascript.html
Please try this:
请试试这个:
Hope this help :)
希望这有帮助 :)
Also note you might not need to check if it contains New
or not, because regex will change if need be:
另请注意,您可能不需要检查它是否包含New
,因为如果需要,正则表达式会更改:
// $("a:contains('New')").each(function () { // NOT sure if you need this
$(this).html($(this).html().replace(/New/g, "<span class='new'>New</span>"));
// });
回答by Ricardo Alvaro Lohmann
Have you tried your code ?
It's working well as you can see here, the only problem is that you forgot to use g
modifier to replace all "New"
ocurrences.
你试过你的代码吗?
正如您在此处看到的那样,它运行良好,唯一的问题是您忘记使用g
修饰符来替换所有"New"
事件。
Other problem is that you don't need each loop, as you can see the following code do the same thing.
The difference is that it's not necessary to loop and get item html twice.
另一个问题是你不需要每个循环,因为你可以看到下面的代码做同样的事情。
不同之处在于没有必要循环并获取项目 html 两次。
$("a:contains('New')").html(function(i, text) {
return text.replace(/New/g, '<span class="new">New</span>');
});