最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - removing spaces between numbers with regex - Stack Overflow

programmeradmin1浏览0评论

am making a form validation, and i need to replace all spaces in the phone input, there for i created this regexp that seems not to be working for reasons i don't know
Demo
this is the code i tried : /(\d)[().\-\s]+(\d)/g
i expect to get : 1 2 3 4 5 6 7 bee 1234567
note that i can't use element.val().replace(/\s/g,'') because the input has other text that will be damaged with this action
so it got to be my code, and if it has a problem i must sort it out
i wish to know more why the regexp is returning the first match only even if i have the g modifier, if anyone could explain me that, thank you

am making a form validation, and i need to replace all spaces in the phone input, there for i created this regexp that seems not to be working for reasons i don't know
Demo
this is the code i tried : /(\d)[().\-\s]+(\d)/g
i expect to get : 1 2 3 4 5 6 7 bee 1234567
note that i can't use element.val().replace(/\s/g,'') because the input has other text that will be damaged with this action
so it got to be my code, and if it has a problem i must sort it out
i wish to know more why the regexp is returning the first match only even if i have the g modifier, if anyone could explain me that, thank you

Share Improve this question asked Sep 21, 2014 at 20:09 user3423014user3423014
Add a ment  | 

1 Answer 1

Reset to default 8

You could use

var str = "hello world 1 2 3 4 5 6 hello world";
var re = /(\d)\s+(?=\d)/g;
str.replace(re, '$1');

Output

"hello world 123456 hello world"

Visualization of regexp

发布评论

评论列表(0)

  1. 暂无评论