OK, I know if I have say the character '-' and I want to remove it in all places in a string with JavaScript, I simply ...
someWord = someWord.replace(/-/g, '');
But, when applying this to an array of characters, it s not working ...
const badChars = ('\/:*?"<>|').split('');
let fileName = title.replace(/ /g, '-').toLocaleLowerCase();
for (let item = 0; item < badChars.length; item++) {
// below will not work with global '/ /g'
fileName = fileName.replace(/badChars[item]/g, '');
}
Any ideas?
/badChars[item]/g
looks for badChars
, literally, followed by an i
, t
, e
, or m
.
If you're trying to use the character badChars[item]
, you'll need to use the RegExp
constructor, and you'll need to escape any regex-specific characters.
Escaping a regular expression has already been well-covered . So using that:
fileName = fileName.replace(new RegExp(RegExp.quote(badChars[item]), 'g'), '');
But , you really don't want that. You just want a character class:
let fileName = title.replace(/[\/:*?"<>|]/g, '-').toLocaleLowerCase();
找到了 ....
fileName = fileName.replace(/[-\/\\^$*+?.()|[\]{}]/g, '');
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.