-2

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;
        }
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
edsamiracle
  • 753
  • 3
  • 12
  • 27
  • 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 Nov 05 '12 at 05:59
  • possible duplicate of [How can you convert blank spaces to   in javascript](http://stackoverflow.com/questions/1170154/how-can-you-convert-blank-spaces-to-nbsp-in-javascript) – Matt Ball Nov 05 '12 at 06:01
  • \s matches whitespace (spaces, tabs and new lines). – Arun Killu Nov 05 '12 at 06:03
  • Have a look at [Convert special characters to HTML in Javascript](http://stackoverflow.com/questions/784586/convert-special-characters-to-html-in-javascript) – Dan Dascalescu Nov 05 '12 at 06:10

2 Answers2

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, ' ');
Community
  • 1
  • 1
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • my function replaces <,>,",& with < > " & however it doesn't replace spaces with &nbsp – edsamiracle Nov 05 '12 at 06:03
  • 2
    Might be better to use `/ /g` - OP probably doesn't want to replace all whitespace, just actual space characters. Also I suspect each individual space should be replaced, not each group of spaces, so no `+`. @aedz - changing a space to ` ` is not "escaping". – nnnnnn Nov 05 '12 at 06:06
0
function escapeHTMLEncode(str) 
 {
   var reg = new RegExp(" ","g");//remove only space 
   return   str.replace(reg,"&nbsp;");//replace space with &nbsp;
  } 
Arun Killu
  • 13,581
  • 5
  • 34
  • 61