user1177440
user1177440

Reputation:

JavaScript - Replace variable from string in all occurrences

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?

Upvotes: 0

Views: 75

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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

Upvotes: 3

user1177440
user1177440

Reputation:

Found it ....

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

Upvotes: 1

Related Questions