Question

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.

Was it helpful?

Solution

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()">

OTHER TIPS

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&nbsp;");
});

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.

var str = 'When you want to change the DispFormUrl'.replace(/ /g, '&nbsp;');
alert(str);

result: "When you want to change the DispFormUrl"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top