I want to replace every "New" inside every link with span tag.
Is it right?
$("a:contains('New')").each(function () {
$(this).html($(this).html().replace("New", "<span class='new'>New</span>"));
});
I want to replace every "New" inside every link with span tag.
Is it right?
$("a:contains('New')").each(function () {
$(this).html($(this).html().replace("New", "<span class='new'>New</span>"));
});
Share
Improve this question
asked Jul 4, 2012 at 23:02
user1299846user1299846
3873 gold badges8 silver badges16 bronze badges
0
3 Answers
Reset to default 7Regex : Working Demo http://jsfiddle/WujTJ/
g = /g modifier makes sure that all occurrences of "replacement"
i - /i makes the regex match case insensitive.
A good read: if you keen: 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:
// $("a:contains('New')").each(function () { // NOT sure if you need this
$(this).html($(this).html().replace(/New/g, "<span class='new'>New</span>"));
// });
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.
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.
$("a:contains('New')").html(function(i, text) {
return text.replace(/New/g, '<span class="new">New</span>');
});
demo
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?
Edit:
Ricardo Lohmann's answer is better, kills the each() function:
$("a:contains('New')").html(function(i, text) {
return text.replace(/New/g, '<span class="new">New</span>');
});