[removed] replace last occurrence of text in a string

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

    Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

    str = str.substring(0, str.length - list[i].length) + "finish"

    0 讨论(0)
  • 2020-12-02 18:36

    I would suggest using the replace-last npm package.

    var str = 'one two, one three, one four, one';
    var result = replaceLast(str, 'one', 'finish');
    console.log(result);
    <script src="https://unpkg.com/replace-last@latest/replaceLast.js"></script>

    This works for string and regex replacements.

    0 讨论(0)
  • 2020-12-02 18:37

    I know this is silly, but I'm feeling creative this morning:

    'one two, one three, one four, one'
    .split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
    .reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
    .join(' ') // string: "one four, one three, one two, one"
    .replace(/one/, 'finish') // string: "finish four, one three, one two, one"
    .split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
    .reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
    .join(' '); // final string: "one two, one three, one four, finish"
    

    So really, all you'd need to do is add this function to the String prototype:

    String.prototype.replaceLast = function (what, replacement) {
        return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
    };
    

    Then run it like so: str = str.replaceLast('one', 'finish');

    One limitation you should know is that, since the function is splitting by space, you probably can't find/replace anything with a space.

    Actually, now that I think of it, you could get around the 'space' problem by splitting with an empty token.

    String.prototype.reverse = function () {
        return this.split('').reverse().join('');
    };
    
    String.prototype.replaceLast = function (what, replacement) {
        return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
    };
    
    str = str.replaceLast('one', 'finish');
    
    0 讨论(0)
  • 2020-12-02 18:38

    Well, if the string really ends with the pattern, you could do this:

    str = str.replace(new RegExp(list[i] + '$'), 'finish');
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题