【问题标题】:replace words in a string from an array of string [duplicate]从字符串数组中替换字符串中的单词[重复]
【发布时间】:2020-11-09 17:39:34
【问题描述】:

我收到一个我想从某个单词中清除的字符串,我试图为此创建一个函数,但它不起作用:

export const cleanArrondissements = async (city) => {

  const arrondissements = [ 'Arrondissement', 'arrondissement', '1er','2e','3e', '4e', '5e', '6e', '7e', '8e', '9e', '10e','11e','12e','13e','14e', '15e', '16e', '17e', '18e', '19e', '20e']
  arrondissements.forEach(element => {
    city.replace(element, '')
  });
  return city;

}

最好的方法是什么?

【问题讨论】:

标签: javascript replace


【解决方案1】:

replace() 方法在字符串中搜索指定值或正则表达式,并返回替换指定值的新字符串

所以用替换你不会改变元素。你需要分配给你的变量来接受替换方法的变化。

export const cleanArrondissements = async (city) => {   
  const arrondissements = [ 'Arrondissement', 'arrondissement', '1er','2e','3e', '4e', '5e', '6e', '7e', '8e', '9e', '10e','11e','12e','13e','14e', '15e', '16e', '17e', '18e', '19e', '20e']
  arrondissements.forEach(element => {
    city=city.replace(element, '')
  });
  return city;
}

如果你可能在基本字符串中有多个相同的元素,那么你可以使用正则表达式

city=city.replace(new RegExp(element, 'g'), '')

【讨论】:

    【解决方案2】:

    Reduce 让它更干净:

    const cleanArrondissements = (city) => {
        
          const arrondissements = [ 'Arrondissement', 'arrondissement', '1er','2e','3e', '4e', '5e', '6e', '7e', '8e', '9e', '10e','11e','12e','13e','14e', '15e', '16e', '17e', '18e', '19e', '20e']
          
          return arrondissements.reduce((acc, cur) => acc.replace(cur, ""), city);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多