views:

50

answers:

4

Whatever string is given I have to see if there is exactly one space after and before =, If it is more than one space in either side I have to reduce that to one and if there is none, I have to insert one.

How should I do that ? String can contain anything.

Thanks

+2  A: 

You can do this:

str = str.replace(/ *= */g, " = ");

This will replace all = characters regardless of how many spaces it is surrounded by. The * quantifier will match as most spaces as possible while allowing even no spaces at all.

Gumbo
+1  A: 

Try this:

var out = in.replace(/ *= */g, " = ");

Basically just replace zero or more instances of a space with a space and you get both desired results. If zero, then you get one. If more than one, you get one.

cletus
+1  A: 

Make the following replacement:

s = s.replace(/ *= */g, ' = ')
Mark Byers
+1  A: 
myString.replace(/\s*=\s*/g, " = ")

will do the same as other given answers, but allow any type of space characters to be replaced (spaces, tabs, etc.).

jkasnicki