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.
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.
Share Improve this question edited Feb 18, 2010 at 7:18 Andrew Moore 95.5k30 gold badges166 silver badges175 bronze badges asked Feb 18, 2010 at 7:09 Josef RichterJosef Richter 5071 gold badge9 silver badges16 bronze badges3 Answers
Reset to default 4you 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"