JavaScript - Replace variable from string in all occurrences

时间:2015-10-30 22:00:45

标签: javascript replace

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?

2 个答案:

答案 0 :(得分:3)

/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();

答案 1 :(得分:1)

Found it ....

   fileName = fileName.replace(/[-\/\\^$*+?.()|[\]{}]/g, '');