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

var string = '#Please send_an_information_pack_to_the_following_address:';

我试过了:

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

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


当前回答

使用OR运算符(|):

Var STR = '#this #is__ __#a test###__'; console.log ( Str.replace (/#|_/g, ") // "this is a test" )

你也可以使用字符类:

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

小提琴

如果你想用一个东西替换散列,用另一个东西替换下划线,那么你只需要链

函数allReplace(str, obj) { For (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } 返回str; }; console.log ( allReplace (abcd-abcd, {' a ': ' h ', ' b ': ' o ' } ) // ' hocd-hocd” );

为什么不加链子呢?我看不出这有什么不对。

其他回答

第二次更新

我开发了以下功能用于生产,也许它可以帮助其他人。它基本上是原生的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.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

如果匹配==“#”,则替换将选择“”,如果不匹配则选择“”。

对于一个更通用的解决方案,你可以将替换字符串存储在一个对象中:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})

如果你想替换多个字符,你可以调用String.prototype.replace(),替换参数是为每个匹配调用的函数。您所需要的只是一个表示将在该函数中使用的字符映射的对象。

例如,如果你想用x替换a,用y替换b,用z替换c,你可以这样做:

Const chars = { a:“x”, b:‘y’, “c”:“z” }; Let s = ' 234abc567bbbac '; S = S .replace(/[abc]/g, m => chars[m]); console.log(年代);

输出:234xyz567yyyyxz

还可以将RegExp对象传递给replace方法,如

var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");

string.replace(regexHash, "").replace(regexUnderscore, " ");

Javascript RegExp

使用OR运算符(|):

Var STR = '#this #is__ __#a test###__'; console.log ( Str.replace (/#|_/g, ") // "this is a test" )

你也可以使用字符类:

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

小提琴

如果你想用一个东西替换散列,用另一个东西替换下划线,那么你只需要链

函数allReplace(str, obj) { For (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } 返回str; }; console.log ( allReplace (abcd-abcd, {' a ': ' h ', ' b ': ' o ' } ) // ' hocd-hocd” );

为什么不加链子呢?我看不出这有什么不对。