user16168
user16168

Reputation: 645

regular expression put space between number and character

I wonder how can I write regular expression to put a space between number and character only if this character not % and not space.

var str = "... 15a...".replace(/(\d+)(\D+)/g,'$1 $2')

The above doesn't work as I expect, for example I need the following constraints

"... 15a ..." => "... 15 a ..."
"... 15 a ..." => "... 15 a ..."
"... 15% ..." => "... 15% ..."

I would appreciate any help.

Upvotes: 1

Views: 5853

Answers (3)

paulotorrens
paulotorrens

Reputation: 2321

Well, you are trying to find a digit followed by a nondigit, non-percent character. So this:

replace(/(\d)([^\d\s%])/g,'$1 $2')

Should do the trick.

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43235

"... 15a...".replace(/(\d+)([^%\d\s]+?)/g,'$1 $2')   

"... 15 a..."

"... 15 a...".replace(/(\d+)([^%\d\s]+?)/g,'$1 $2')

"... 15 a..."

"... 15%...".replace(/(\d+)([^%\d\s]+?)/g,'$1 $2')

"... 15%..."

Upvotes: 0

aelor
aelor

Reputation: 11116

var str = "... 15a...".replace(/(\d+)([a-z]+)/g,'$1 $2')

Upvotes: 3

Related Questions