0

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
  • You could build a regular expression instead of using a string of characters... something like const badChars = /[\/:*?"<>|]/g; Commented Oct 30, 2015 at 22:03
  • @JamesAllardice—that's what the OP thinks is happening, but it's not. Commented Oct 30, 2015 at 22:11

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

Found it ....

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.