简体   繁体   中英

How do I replace everything(whitespaces/symbols) except letters and numbers in a JavaScript String?

I need to replace every single symbol and whitespace with the minus(-) sign in a string. I am not yet particularly familiar with Regex.

Use negated character set :

If you're okay keeping the underscore, you can use:

str.replace(/[^\w]/g, "-") // \w is the same as [A-Za-z0-9_]

If you want to replace that as well, then you can use:

str.replace(/[^A-Za-z0-9]/g, "-")

Edit: As mentioned by @JamesBuck, there are actually negated shorthands : [^\\w] is the same as \\W , so if you don't need to replace the underscore, you can use that, resulting in:

str.replace(/\W/g, "-")
var str = "djdkasfh da@S@FA";
str.replace(/[^a-z0-9]+/gi, '-');

Outputs djdkasfh-da-S-FA .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM