how to replace last occurrence of a word in javascript?

前端 未结 3 766
不知归路
不知归路 2020-12-20 15:35

for example:

var str=\"
hi
hi\";

to replace the last(second)
,

to change into \"<

相关标签:
3条回答
  • 2020-12-20 16:16

    You can use the fact that quantifiers are greedy:

    str.replace(/(.*)<br>/, "$1");
    

    But the disadvantage is that it will cause backtracking.

    Another solution would be to split up the string, put the last two elements together and then join the parts:

    var parts = str.split("<br>");
    if (parts.length > 1) {
        parts[parts.length - 2] += parts.pop();
    }
    str = parts.join("<br>");
    
    0 讨论(0)
  • 2020-12-20 16:19

    I think you want this:

    str.replace(/^(.*)<br>(.*?)$/, '$1$2')
    

    This greedily matches everything from the start to a <br>, then a <br>, then ungreedily matches everything to the end.

    0 讨论(0)
  • 2020-12-20 16:21
    String.prototype.replaceLast = function(what, replacement) { 
        return this.replace(new RegExp('^(.*)' + what + '(.*?)$'), '$1' + replacement + '$2');
    }
    
    str = str.replaceLast(what, replacement);
    
    0 讨论(0)
提交回复
热议问题