如何使用JavaScript替换字符串中的字符或单词,即使它们之间没有空格?

Arc*_*Arc 6 javascript

我有一个类似这样的功能:

 var exchange = function(code) {
     var ref = {
       'one' : '1' , 
       'two' : '2' ,
       'three' : '3'
     }; 
   return code.split(' ').map( function (a) { 
     return a.split(' ').map( function (b) { 
        return ref[b]; 
     }).join(''); 
   }).join(' '); 
 };
Run Code Online (Sandbox Code Playgroud)

所以现在我做到了:

 var strg = "one two three";
 alert( exchange( strg ) ); // => 123
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我有问题。让我解释。我希望它执行与现在相同的操作,直到之间没有空格。

例如 :

 var strg = "onetwothree";
 alert( exchange( strg ) ); // => Nothing
Run Code Online (Sandbox Code Playgroud)

但是我希望它即使没有空格也可以更改文本。我怎样才能做到这一点 ?

Nin*_*olz 7

您可以使用带管道的连接字符串创建正则表达式,然后将找到的字符串替换为值。

var exchange = function(code) {
        var ref = { one: '1',  two: '2', three: '3' }; 
        return code.replace(new RegExp(Object.keys(ref).join('|'), 'ig'), k => ref[k]);
    };

console.log(exchange("onetwothree"));
Run Code Online (Sandbox Code Playgroud)