[removed] replace last occurrence of text in a string

后端 未结 14 777
一整个雨季
一整个雨季 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:39

    Old fashioned and big code but efficient as possible:

    function replaceLast(origin,text){
        textLenght = text.length;
        originLen = origin.length
        if(textLenght == 0)
            return origin;
    
        start = originLen-textLenght;
        if(start < 0){
            return origin;
        }
        if(start == 0){
            return "";
        }
        for(i = start; i >= 0; i--){
            k = 0;
            while(origin[i+k] == text[k]){
                k++
                if(k == textLenght)
                    break;
            }
            if(k == textLenght)
                break;
        }
        //not founded
        if(k != textLenght)
            return origin;
    
        //founded and i starts on correct and i+k is the first char after
        end = origin.substring(i+k,originLen);
        if(i == 0)
            return end;
        else{
            start = origin.substring(0,i) 
            return (start + end);
        }
    }
    

提交回复
热议问题