[removed] replace last occurrence of text in a string

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

    I did not like any of the answers above and came up with the below

    function replaceLastOccurrenceInString(input, find, replaceWith) {
        if (!input || !find || !replaceWith || !input.length || !find.length || !replaceWith.length) {
            // returns input on invalid arguments
            return input;
        }
    
        const lastIndex = input.lastIndexOf(find);
        if (lastIndex < 0) {
            return input;
        }
    
        return input.substr(0, lastIndex) + replaceWith + input.substr(lastIndex + find.length);
    }
    

    Usage:

    const input = 'ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty';
    const find = 'teen';
    const replaceWith = 'teenhundred';
    
    const output = replaceLastOccurrenceInString(input, find, replaceWith);
    console.log(output);
    
    // output: ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteenhundred twenty
    
    

    Hope that helps!

提交回复
热议问题