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
2 Answers
Reset to default 6Check 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
}