user3423014
user3423014

Reputation:

removing spaces between numbers with regex

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 become 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

Upvotes: 1

Views: 3056

Answers (1)

Mulan
Mulan

Reputation: 135197

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

/(\d)\s+(?=\d)/g

Upvotes: 8

Related Questions