regular expression put space between number and character

走远了吗. 提交于 2021-01-06 04:24:54

问题


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.


回答1:


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



回答2:


"... 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%..."




回答3:


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.



来源:https://stackoverflow.com/questions/23752362/regular-expression-put-space-between-number-and-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!