最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

replace character (space with  ) across whole webpage using javascriptjQuery - Stack Overflow

programmeradmin2浏览0评论

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 &nbsp; to prevent leaving these characters at the end of line, should be something like

myString.replace(/\s\w(?=\s)/,"$1&nbsp;")

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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, '&nbsp;');
alert(str);

result: "When you want to change the DispFormUrl"

发布评论

评论列表(0)

  1. 暂无评论