我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。

var string = '#Please send_an_information_pack_to_the_following_address:';

我试过了:

string.replace('#','').replace('_', ' ');

我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?


当前回答

第二次更新

我开发了以下功能用于生产,也许它可以帮助其他人。它基本上是原生的replaceAll Javascript函数的循环,它没有使用regex:

function replaceMultiple(text, characters){
  for (const [i, each] of characters.entries()) {
    const previousChar = Object.keys(each);
    const newChar = Object.values(each);

    text = text.replaceAll(previousChar, newChar);
  }  
  
return text
}

用法非常简单。下面是使用OP的例子的样子:


const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
    {
    "#":""
    },
   {
    "_":" "
    },
]

const result = replaceMultiple(text, characters);

console.log(result); //'Please send an information pack to the following address:'

更新

现在可以在本地使用replaceAll。

过时的回答

下面是使用字符串原型的另一个版本。享受吧!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }
    
    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"

其他回答

一个函数和一个原型函数。

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'gi'), replacement);
};


            var map = {
                '&': 'and ',
                '[?]': '',
                '/': '',
                '#': '',
                // '|': '#65 ',
                // '[\]': '#66 ',
                // '\\': '#67 ',
                // '^': '#68 ',
                '[?&]': ''
            };


             var map2 = [
                {'&': 'and '},
                {'[?]': ''},
                {'/': ''},
                {'#': ''},                
                {'[?&]': ''}
            ];

            name = replaceAll2(name, map2);
            name = replaceAll(name, map);


    function replaceAll2(str, map) {            
        return replaceManyStr(map, str);
    }  

    function replaceManyStr(replacements, str) {
        return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
    }

在正则表达式上指定/g (global)标志来替换所有匹配项,而不仅仅是第一个:

string.replace(/_/g, ' ').replace(/#/g, '')

要用一种东西替换一个字符,用另一种东西替换另一个字符,你真的不能避免需要两个单独的调用来替换。你可以把它抽象成一个函数,就像门把手做的那样,尽管我可能会让它把一个对象的旧/新作为键/值对,而不是一个平面数组。

对于什么都不替换,tckmn的答案是最好的。

如果你需要替换对应匹配的特定字符串,下面是Voicu和Christophe回答的一个变体,避免重复被匹配的内容,这样你就不必记得在两个地方添加新的匹配:

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]);

你可以试试这个:

str.replace(/[.#]/g, 'replacechar');

这将用你的replacechar !

不知道为什么还没有人提供这个解决方案,但我发现它非常有效:

var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
    "_": " ",
    "#": ""
]

for(var placeholder in placeholders){
    while(string.indexOf(placeholder) > -1) {
        string = string.replace(placeholder, placeholders[placeholder])
    }
}

你可以添加任何你喜欢的占位符,而不必更新你的函数。简单!