tags:

views:

1276

answers:

4

Without using regular expressions, how can you convert blank spaces to   in javascript?

A: 

JavaScript replace() Method

link

http://www.w3schools.com/jsref/jsref_replace.asp

Haim Evgi
+2  A: 
"this is a string".replace(/\s/g, 'nbsp;')

nbsp; should be the full entity ( ). StackOverflow is converting it to a space.

cpharmston
Hmmm... just another bug in the Markdown impl.
Cerebrus
The question did specify "without regular expressions" - and /\s/ is one.
David Dorward
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
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
Technically he could loop over the string and build a new one but it would be really stupid.
Fredrik
Agreed... both about the unusual idea and its relative viability.
Cerebrus
@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
+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
@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
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