How to write a regular expression that removes all characters except numbers and the + character?
|
2 answers
/[^+\d]/g
[...]- character class^- inversion, we will replace "everything except"+- the + symbol, you can screen:\+, but inside the character class it is not necessary\d- digit/.../g- global flag for replace - change all occurrences
let str = 'call: +7(123) 456-78-90'; console.log(str.replace(/[^+\d]/g, '')); - Plus not shielded. - user218976
- And why should it be screened in a character class ?? - vp_arth
- one@Anamnian and why should it be screened in this case (in the character set)? - Regent
- You are right, I was wrong. It is not necessary to screen it. Although it is clearer to me with shielding. - user218976
- 2@Anamnian ... then, it means that at some point in the development something went wrong, since such a regression appeared :) For I do not want to sit around to understand and correct errors in such an expression from the word "completely". And, I think,
+instead of\+in[]when parsing it will be the lesser of problems - Regent
|
Let's go from the reverse, just take any character except the number and +
const regEx = /[^\d\+]/g; const test = '123gybbrry45ybg6=789,m er+' console.log(test.replace(regEx, '')); |
/[^\d\+]/g? (2 characters) - user218976