简体   繁体   English

JavaScript-多次替换字符串中的变量

[英]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 ... 好的,我知道我是否说过字符“-”,并且想使用JavaScript在字符串中的所有位置将其删除,我只是...

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 . /badChars[item]/g从字面上查找badChars ,后跟item

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. 如果尝试使用字符badChars[item] ,则需要使用RegExp构造函数,并且需要转义任何正则表达式特定的字符。

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, '');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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