最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove all the characters and special characters except underscores, dashes and numbers - Stack Overflow

programmeradmin3浏览0评论

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_.

Share Improve this question asked May 20, 2020 at 12:39 Christian RuggieroChristian Ruggiero 431 silver badge5 bronze badges 2
  • 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
Add a ment  | 

1 Answer 1

Reset to default 6

This 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, \-.)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论