replace character (space with ) across whole webpage using javascript/jQuery
So I figured out that the replace function, that finds all single-letter "words" (prepositions and conjunction, etc.) and replace the space after them with a
to prevent leaving these characters at the end of line, should be something like
myString.replace(/\s\w(?=\s开发者_开发知识库)/,"$1 ")
Now how do I apply it to all text on a webpage? I am looking for some universal solution, a simple function which I put into <head>
without need to change anything else in the webpage.
Thank you very much.
you could try something like this:
$('body').contents().filter(function(){
return this.nodeType == 3;
}).each(function(){
this.nodeValue = this.nodeValue.replace(/\s\w(?=\s)/,"$1 ");
});
Basically we grab the body element and get its contents - the contents()
method will grab text nodes as well as elements which is what we want. Then we filter on nodeType reducing the set to only text nodes. then we do the regex replace.
function replaceText(node)
{
var current = node.nodeValue;
var replaced = current.replace(searchpattern, replacepattern);
node.nodeValue = replaced;
}
function traverse(node)
{
var children = node.childNodes;
var childLen = children.length;
for(var i = 0; i < childLen; i++)
{
var child = children.item(i);
if(child.nodeType == 3)//or if(child instanceof Text)
replaceText(child);
else
traverse(child);
}
}
function replaceAll()
{
traverse(document.body);
}
Call replaceAll()
from body's onload
.
<body onload="replaceAll()">
var str = 'When you want to change the DispFormUrl'.replace(/ /g, ' ');
alert(str);
result: "When you want to change the DispFormUrl"
精彩评论