[removed] replace last occurrence of text in a string

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

    Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:

    function removeLastInstance(badtext, str) {
        var charpos = str.lastIndexOf(badtext);
        if (charpos<0) return str;
        ptone = str.substring(0,charpos);
        pttwo = str.substring(charpos+(badtext.length));
        return (ptone+pttwo);
    }
    

    I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)

提交回复
热议问题