Replace multiple characters in one replace call

前端 未结 15 2300
失恋的感觉
失恋的感觉 2020-11-22 17:24

Very simple little question, but I don\'t quite understand how to do it.

I need to replace every instance of \'_\' with a space, and every instance of \'#\' with no

15条回答
  •  清酒与你
    2020-11-22 17:28

    For replacing with nothing, tckmn's answer is the best.

    If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

    const replacements = {
      '’': "'",
      '“': '"',
      '”': '"',
      '—': '---',
      '–': '--',
    };
    const replacement_regex = new RegExp(Object
      .keys(replacements)
      // escape any regex literals found in the replacement keys:
      .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
      .join('|')
    , 'g');
    return text.replace(replacement_regex, e => replacements[e]);
    

提交回复
热议问题