Javascript or jQuery replace text
I need to replace some text that is on the page within the body tag. I am using javascript but have jquery available if needed. I basically need to replace test® (test with the registered trademark) with TEST® or tests® with TESTS® and it could even be test with TEST® or tests with TESTS®. I am able to uppercase them but its not liking to work for me with the ® sign, it wants to put duplicates on ones that already have it. Basically anything on the page that has the word test or tests should be TEST®开发者_StackOverflow中文版; or TESTS® if it is plural. Any help is appreciated.
EDIT:
So now I have this:var html = $('body').html();
var html = html.replace(/realtor(s)?(®)?/gi, function(m, s1, s2){
var s = s1?s1.toUpperCase():"";
var reg = s2?s2:'®';
return "REALTOR"+s+reg;
});
$('body').html(html);
Its working well other than it is duplicating the ® on the ones that already had them any ideas on how not to?
As others have already said, you will not be able to match the ®
, you need to match on
\u00ae
.
The code you provided needs to be changed to:
var html = $('body').html();
var html = html.replace(/realtor(s)?(\u00ae)?/gi, function(m, s1, s2){
var s = s1?s1.toUpperCase():"";
var reg = s2?s2:'®';
return "REALTOR"+s+reg;
});
$('body').html(html);
To expand on jAndy's answer, try this:
$("div, p, span").each(function(){
o = $(this);
o.html( o.text().replace(/test(|s)\u00ae/gi, function($1){
return($1.toUpperCase());
}));
});
Using the code you provided, try this:
$(document).ready(function(){
$('body').html( $('body').html().replace(/realtor(|s)\u00ae/gi, function($1){
return($1.toUpperCase() );
}));
})
Instead of creating something from scratch try using an alternate library. I develop with PHP so using a library that has identical methods in JavaScript is a life saver.
PHP.JS Library
var newReplaced = $P.str_replace("find","replace",varSearch);
The tricky part here is to match the ®, which is a Unicode character, I guess... Have you tried the obvious?
var newStr = str.replace(/test(s)?®?/gi, function(m, s1){
var s = s1?s1.toUpperCase():"";
return "TEST"+s+"®";
});
If the problem is that ®
does not match, try with its unicode character number:
/test(s)?\u00ae/
Sorry if the rest does not work, I assume your replacement already works and you just have to also match the ® so that it does not get duplicated.
精彩评论