Replace string with values from two arrays

前端 未结 6 1676
渐次进展
渐次进展 2021-01-16 07:09

I have a string for example:

var string = \'This is a text that needs to change\';

And then I have two arrays.

var array1 =         


        
6条回答
  •  醉话见心
    2021-01-16 07:32

    For the purpose of exploring other interesting methods of doing the same thing, here is an implementation using array map.

    It's just another cool way of doing it, without using a loop, replace or regexp.

    var string = 'This is a text that needs to change';
    var array1 = ['a', 'e', 'i', 'o', 'u'];
    var array2 = ['1', '2', '3', '4', '5'];
    
    var a = string.split('');
    a.map(function(c) {
        if (array1.indexOf(c) != -1) {
            a[ a.indexOf(c) ] = array2[ array1.indexOf(c) ];
        }
    });
    
    var newString = a.join('');
    alert( newString );
    //Outputs "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"
    

    Demo: JSFiddle

    Interesting blog post about the array methods - map and reduce.

    I'd love to hear thoughts about performance of array map vs the other methods.

提交回复
热议问题