Reputation: 3705
I want to validate and process a string, which should be a telephone number. For the first character, numbers and + is accepted, for the rest, just numbers.
I have the solution to accept + and numbers, but just for the whole string:
console.log("asd242++asf43+234".replace(/[^+\d]/g, ""))
But suffering from defining different check for the first character, and the rest.
Upvotes: 0
Views: 1434
Reputation: 2587
You can use the following:
([^+\d]|(?!^)\+)
It matches everything that is not a digit nor a +
and doesn't match +
at the beginning of the string!
So your test log would look like this:
console.log("+asd242++asf43+234".replace(/([^+\d]|(?!^)\+)/g, ""))
(i added a +
to the beginning to show it handles this correctly!)
See a Demo that shows it matches all your cases!
Upvotes: 1
Reputation: 31
Try this one:
/^[+]?[0-9]+$/g
^ - start of string
[+]? - single optional + character
[0-9]+ - one or more digit
$ - end of string
Upvotes: 0
Reputation: 36574
What I understood you want to validate +numbers
. You should use ^
and $
in start of end of your regex. I think following regex will work if i am not wrong.
/^\+[0-9]+$/
Upvotes: 0