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.
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")
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With