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

html - javascript function to replace space - Stack Overflow

programmeradmin1浏览0评论

Hi can you give me a javascript function to replace spaces with  

i googled and can't get them to work. I'm currently using this function:

  function escapeHTMLEncode(str) 
        {
            var div = document.createElement('div');
            var text = document.createTextNode(str);
            div.appendChild(text);
            return div.innerHTML;
        }

Hi can you give me a javascript function to replace spaces with  

i googled and can't get them to work. I'm currently using this function:

  function escapeHTMLEncode(str) 
        {
            var div = document.createElement('div');
            var text = document.createTextNode(str);
            div.appendChild(text);
            return div.innerHTML;
        }
Share Improve this question edited Nov 5, 2012 at 5:56 Matt Ball 360k102 gold badges653 silver badges720 bronze badges asked Nov 5, 2012 at 5:55 edsamiracleedsamiracle 7933 gold badges13 silver badges27 bronze badges 4
  • This code works for characters which must actually be escaped in HTML, such as > (escaped as >). But   is not the same thing as a space character. – Matt Ball Commented Nov 5, 2012 at 5:59
  • possible duplicate of How can you convert blank spaces to   in javascript – Matt Ball Commented Nov 5, 2012 at 6:01
  • \s matches whitespace (spaces, tabs and new lines). – Arun Killu Commented Nov 5, 2012 at 6:03
  • Have a look at Convert special characters to HTML in Javascript – Dan Dascalescu Commented Nov 5, 2012 at 6:10
Add a ment  | 

2 Answers 2

Reset to default 6

Check out regular expressions:

return str.replace(/\s+/g, ' ');

However, the name of your function, escapeHTMLEncode, suggests you want to do more than just replace spaces. Can you clarify your question? See also Convert special characters to HTML in Javascript, which seems to be what you're trying to do.

Note that the \s+ pattern will match any sequence of consecutive whitespace. If you want to replace only space characters (), and replace each of them with  , use

return str.replace(/ /g, ' ');
function escapeHTMLEncode(str) 
 {
   var reg = new RegExp(" ","g");//remove only space 
   return   str.replace(reg," ");//replace space with  
  } 
发布评论

评论列表(0)

  1. 暂无评论