I'm trying again to replace each text content of each control in a page using javascript and jquery.
I need to search in each text content (WITHOUT MODIFING TAGS开发者_StackOverflow中文版, ONLY THE TEXT) any word and replace it with another any word.
One try is:
jQuery.fn.replaceEachOne = function (objective, rep) {
this.each( function(){
//$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
$(this).html( $(this).html().replace( new RegExp('('+objective+'(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
}
);
}
Please help!!
Something like this should do the trick:
$.fn.replaceEachOne = function(search, replace) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(search, replace);
} else if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = this.nodeValue.replace(search, replace);
}
});
};
This does the replacement on text nodes directly, rather than modifying the HTML of an entire element. Note that it is case-sensitive. You'd need to change the call to replace
to use a regular expression if you want a case-insensitive search.
I would start by something like this:
jQuery.fn.replaceEachOne = function(objective, rep) {
var html = jQuery(this).html();
var simpleRegexp = new RegExp(objective, "gi");
var regexp = new RegExp(">[^><]*?"+objective+"[^><]*?<","gi");
html = html.replace(regexp, function(match) {
return match.replace(simpleRegexp, rep);
});
jQuery(this).html(html);
}
That code finds the matching text in body html code beetween '>'
and '<'
characters and then replaces matched text.
Of course this is simple solution and it will replace text also in <script>
or <style>
blocks. By I think it is a good idea to start with.
Finally...
jQuery.fn.replaceEachOne = function (objective, reposition) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(objective, reposition);
} else if (this.nodeType == Node.TEXT_NODE) {
var label = document.createElement("label");
label.innerHTML = this.nodeValue.replace(objective, reposition);
this.parentNode.insertBefore(label, this);
this.parentNode.removeChild(this);
}
});
}
精彩评论