Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing every non-digit character except a plus (+) sign in phone number

I want to alter a text string with a regular expression, removing every non-digit character, except a + sign. But only if it's the first character

   +23423424dfgdgf234 --> +23423424234
   2344  234fsdf  9   --> 23442349
   4+4                --> 44

etc

The replacing of 'everything but' is pretty simple:
/[^\+|\d]/gi but that also removes the +-sign as a first character.

how can I alter the regexp to get what I want?

If it matters: I'm using the regexp in javascript's str.replace() function.

like image 590
stUrb Avatar asked Jan 22 '26 23:01

stUrb


2 Answers

I would do it in two steps, first removing everything that must be removed apart the +, then the + that aren't the first char :

var str2 = str1.replace(/[^\d\+]+/g,'').replace(/(.)\++/g,"$1")
like image 130
Denys Séguret Avatar answered Jan 24 '26 18:01

Denys Séguret


You'd have to do this in two steps:

// pass one - remove all non-digits or plus
var p1 = str.replace(/[^\d+]+/g, ''); 
// remove plus if not first
var p2 = p1.length ? p1[0] + p1.substr(1).replace(/\+/g, '') : '';

console.log(p2);
like image 40
Ja͢ck Avatar answered Jan 24 '26 17:01

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!