Javascript 如何替换字符串中的多个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44324892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:27:20  来源:igfitidea点击:

How can I replace multiple characters in a string?

javascriptregex

提问by Gabriel

I want to create a regex with following logic: 1., If string contains Treplace it with space 2., If string contains Zremove Z

我想用以下逻辑创建一个正则表达式:1., 如果字符串包含T用空格替换它 2., 如果字符串包含Z删除Z

I wrote two regex already, but I can't combine them:

我已经写了两个正则表达式,但我不能将它们组合起来:

string.replace(/\T/g,' ') && string.replace(/\Z/g,'');

EDIT: I want the regex code to be shorter

编辑:我希望正则表达式代码更短

回答by LukStorms

Doesn't seem this even needs regex. Just 2 chained replacements would do.

似乎这甚至不需要正则表达式。只需 2 个链式替换即可。

var str = '[T] and [Z] but not [T] and [Z]';
var result = str.replace('T',' ').replace('Z','');
console.log(result);

However, a simple replaceonly replaces the first occurence.
To replace all, regex still comes in handy. By making use of the global gflag.
Note that the characters aren't escaped with \. There's no need.

但是,简单replace仅替换第一次出现。
要全部替换,regex 仍然派上用场。通过使用全局g标志。
请注意,字符没有用 转义\。没有必要。

var str = '[T] and [Z] and another [T] and [Z]';
var result = str.replace(/T/g,' ').replace(/Z/g,'');
console.log(result);

// By using regex we could also ignore lower/upper-case. (the i flag)
// Also, if more than 1 letter needs replacement, a character class [] makes it simple.
var str2 = '(t) or (?) and (z) or (?). But also uppercase (T) or (Z)';
var result2 = str2.replace(/[t?]/gi,' ').replace(/[z?]/gi,'');
console.log(result2);

But if the intention is to process really big strings, and performance matters?
Then I found out in another challengethat using an unnamed callback function inside 1 regex replace can prove to be faster. When compared to using 2 regex replaces.

但是,如果目的是处理非常大的字符串,那么性能很重要吗?
然后我在另一个挑战中发现,在1 个正则表达式替换中使用未命名的回调函数可以证明更快。与使用 2 个正则表达式替换相比。

Probably because if it's only 1 regex then it only has to process the huge string once.

可能是因为如果它只有 1 个正则表达式,那么它只需要处理一次巨大的字符串。

Example snippet:

示例片段:

console.time('creating big string');
var bigstring = 'TZ-'.repeat(2000000);
console.timeEnd('creating big string');

console.log('bigstring length: '+bigstring.length);

console.time('double replace big string');
var result1 = bigstring.replace(/[t]/gi,'X').replace(/[z]/gi,'Y');
console.timeEnd('double replace big string');

console.time('single replace big string');
var result2 = bigstring.replace(/([t])|([z])/gi, function(m, c1, c2){
         if(c1) return 'X'; // if capture group 1 has something
         return 'Y';
       });
console.timeEnd('single replace big string');

var smallstring = 'TZ-'.repeat(5000);

console.log('smallstring length: '+smallstring.length);

console.time('double replace small string');
var result3 = smallstring.replace(/T/g,'X').replace(/Z/g,'Y');
console.timeEnd('double replace small string');

console.time('single replace small string');
var result4 = smallstring.replace(/(T)|(Z)/g, function(m, c1, c2){
         if(c1) return 'X'; 
         return 'Y';
       });
console.timeEnd('single replace small string');

回答by maioman

you can capture both and then decide what to do in the callback:

您可以捕获两者,然后决定在回调中做什么:

string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));

var string = 'AZorro Tab'

var res = string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));

console.log(res)

-- edit --

- 编辑 -

Using a dict substitution you can also do:

使用 dict 替换,您还可以执行以下操作:

var string = 'AZorro Tab'

var dict = { T : '', Z : ' '}

var re = new RegExp(`[${ Object.keys(dict).join('') }]`,'g')

var res = string.replace(re,(m => dict[m] ) )

console.log(res)

回答by Clujio

Do you look for something like this?

你在寻找这样的东西吗?

ES6

ES6

var key = {
  'T': ' ',
  'Z': ''
}
"ATAZATA".replace(/[TZ]/g, (char) => key[char] || '');

Vanilla

香草

"ATAZATA".replace(/[TZ]/g,function (char) {return key[char] || ''});

or

或者

"ATAZATA".replace(/[TZ]/g,function (char) {return char==='T'?' ':''});

回答by Diego Fortes

Here is another alternative using string.prototype:

这是使用的另一种选择string.prototype

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"