JavaScript:替换字符串中最后一次出现的文本

147

请看下面的代码片段:

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         str = str.replace(list[i], 'finish')
     }
 }
我想将字符串中最后一个单词“one”替换为“finish”,但我现在的方法不起作用,因为replace方法只会替换第一个。有谁知道我该如何修改代码片段,以便它仅替换最后一个“one”的实例?
16个回答

3
如果速度很重要的话,请使用以下内容:
/**
 * Replace last occurrence of a string with another string
 * x - the initial string
 * y - string to replace
 * z - string that will replace
 */
function replaceLast(x, y, z){
    var a = x.split("");
    var length = y.length;
    if(x.lastIndexOf(y) != -1) {
        for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
            if(i == x.lastIndexOf(y)) {
                a[i] = z;
            }
            else {
                delete a[i];
            }
        }
    }

    return a.join("");
}

它比使用正则表达式更快。


2
function replaceLast(text, searchValue, replaceValue) {
  const lastOccurrenceIndex = text.lastIndexOf(searchValue)
  return `${
      text.slice(0, lastOccurrenceIndex)
    }${
      replaceValue
    }${
      text.slice(lastOccurrenceIndex + searchValue.length)
    }`
}

0
if (string.search(searchstring)>-1) {
    stringnew=((text.split("").reverse().join("")).replace(searchstring, 
    subststring).split("").reverse().join(""))
    }

//with var string= "sdgu()ert(dhfj ) he ) gfrt"
//var searchstring="f"
//var subststring="X"
//var stringnew=""
//results in
//string    :  sdgu()ert(dhfj ) he ) gfrt
//stringnew :  sdgu()ert(dhfj ) he ) gXrt

@pguardiario的答案是迄今为止最通用和优雅的解决方案。 - Aurovrata

0

虽然代码老旧而且庞大,但尽可能高效。

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
我建议使用 replace-last npm 包。

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>

这适用于字符串和正则表达式替换。


-1
str = (str + '?').replace(list[i] + '?', 'finish');

8
通常情况下,除了答案之外,人们通常也需要解释。 - user4413591

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接