Search code examples
javascripthtmlencodespace

javascript function to replace space


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;
        }

Solution

  • 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, ' ');