[removed] replace last occurrence of text in a string

后端 未结 14 783
一整个雨季
一整个雨季 2020-12-02 18:13

See my code snippet below:

var list = [\'one\', \'two\', \'three\', \'four\'];
var str = \'one two, one three, one four, one\';
for ( var i = 0; i < list.         


        
14条回答
  •  执笔经年
    2020-12-02 18:30

    If speed is important, use this:

    /**
     * Replace last occurrence of a string with another string
     * x - the initial string
     * y - string to replace
     * z - string that will replace
     */
    function replaceLast(x, y, z){
        var a = x.split("");
        var length = y.length;
        if(x.lastIndexOf(y) != -1) {
            for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
                if(i == x.lastIndexOf(y)) {
                    a[i] = z;
                }
                else {
                    delete a[i];
                }
            }
        }
    
        return a.join("");
    }
    

    It's faster than using RegExp.

提交回复
热议问题