Without using regular expressions, how can you convert blank spaces to
in javascript?
views:
1276answers:
4
A:
Haim Evgi
2009-07-23 07:22:13
+2
A:
"this is a string".replace(/\s/g, 'nbsp;')
nbsp;
should be the full entity (
). StackOverflow is converting it to a space.
cpharmston
2009-07-23 07:22:24
Hmmm... just another bug in the Markdown impl.
Cerebrus
2009-07-23 07:32:04
The question did specify "without regular expressions" - and /\s/ is one.
David Dorward
2009-07-23 09:03:26
True, see below for an example of one without regex. This has the added benefit of converting other whitespace unicode characters (non-breaking spaces, etc) in one fell swoop.
cpharmston
2009-07-23 13:45:56
A:
To answer the question, No, there isn't a way to do this without using Regex/String replace.
As others have indicated, using the JS String object methods such as replace()
is your best bet.
Cerebrus
2009-07-23 07:38:36
Technically he could loop over the string and build a new one but it would be really stupid.
Fredrik
2009-07-23 07:42:09
@Cerebus: This answer is incorrect. There are MANY ways to do this without using Regex/String replace. Those ways may be stupid and less efficient, but it is wrong to say there is no other way to do it.
Grant Wagner
2009-07-23 14:58:23
+2
A:
So, when you said "Without using regular expressions" you meant "Using regular expressions".
FWIW, you can do it without regular expressions using
"This is a string".split(" ").join(" ");
NickFitz
2009-07-23 13:29:53
@NickFitz: I took the liberty of editing your answer so ` ` shows up correctly. And +1 for providing the only answer that actually answers the original question, which is to do it not using regular expressions.
Grant Wagner
2009-07-23 14:57:13
Thanks Grant - I should have noticed that, but my client expects me to do some work occasionally while I'm here rather than reading SO all day ;-)
NickFitz
2009-07-23 15:55:34