Currently having a problem with removing all the alphabetic characters from string except '_', '-' and numbers.My string looks like follows.
let str = '/Anna-Charoline_1985-02-14_London/';
And i have tried following code to remove the unwanted characters.
let formatted = str.replace(/[D&\/\\#,+()$~%.'":*?<>{}]/g, '');
It did't work. Can anyone help me with this please? Expected output is _1985-02-14_
.
Currently having a problem with removing all the alphabetic characters from string except '_', '-' and numbers.My string looks like follows.
let str = '/Anna-Charoline_1985-02-14_London/';
And i have tried following code to remove the unwanted characters.
let formatted = str.replace(/[D&\/\\#,+()$~%.'":*?<>{}]/g, '');
It did't work. Can anyone help me with this please? Expected output is _1985-02-14_
.
-
Way easier with a negated character class -
/[^0-9_-]/g
– C3roe Commented May 20, 2020 at 12:42 -
What the above said + you forgot to add the a-zA-Z selector to remove the letters.
str.replace(/[a-zA-ZD&\/\\#,+()$~%.'":*?<>{}]/g, '')
– Ruckert Solutions Commented May 20, 2020 at 12:42
1 Answer
Reset to default 6This is way easier with a negated character class:
str.replace(/[^0-9_-]/g, '');
Everything that is not a digit between 0 and 9, an underscore or a minus, will get replaced by an empty string.
(The first -
means “range” here, because it is between two other characters, the second one just means “itself”, because it is at the end of the character class. If it was placed somewhere other than the very start or end, it would need to be escaped, \-
.)