0

我想替换字符串中特定单词的多次出现并只保留最后一个。

   "How about a how about b how about c" to ==>
    "a b How about c"

我使用 string.replace 替换所有出现,但我仍然想要最后一个。对不起,如果它很天真

4

3 回答 3

3

一种方法是使用某种循环来检查是否发生了任何事情。

function allButLast(haystack, needle, replacer, ignoreCase) {
    var n0, n1, n2;
    needle = new RegExp(needle, ignoreCase ? 'i' : '');
    replacer = replacer || '';
    n0 = n1 = n2 = haystack;
    do {
        n2 = n1; n1 = n0;
        n0 = n0.replace(needle, replacer);
    } while (n0 !== n1);
    return n2;
}

allButLast("How about a how about b how about c", "how about ", '', 1);
// "a b how about c"
于 2013-10-15T00:37:19.133 回答
1

稍微不同的方法,同时支持 RegExp 和普通字符串针:

var replaceAllBarLast = function(str, needle, replacement){
  var out = '', last = { i:0, m: null }, res = -1;
  /// RegExp support
  if ( needle.exec ) {
    if ( !needle.global ) throw new Error('RegExp must be global');
    while( (res = needle.exec(str)) !== null ) {
      ( last.m ) && ( last.i += res[0].length, out += replacement );
      out += str.substring( last.i, res.index );
      last.i = res.index;
      last.m = res[0];
    }
  }
  /// Normal string support -- case sensitive
  else {
    while( (res = str.indexOf( needle, res+1 )) !== -1 ) {
      ( last.m ) && ( last.i += needle.length, out += replacement );
      out += str.substring( last.i, res );
      last.i = res;
      last.m = needle;
    }
  }
  return out + str.substring( last.i );
}

var str = replaceAllBarLast(
  "How about a how about b how about c", 
  /how about\s*/gi, 
  ''
);

console.log(str);
于 2013-10-15T01:06:34.943 回答
0

无论使用哪种语言,都没有内置方法可以做到这一点。你可以做的是(可能需要调试)

string customReplace(string original, string replaceThis, string withThis)
{
    int last = original.lastIndexOf(replaceThis);
    int index = s.indexOf(replaceThis);
    while(index>=0 && index < last )
     {
        original = original.left(index)+ original.right(index+replaceThis.length);
        last = original.lastIndexOf(replaceThis); // gotta do this since you changed the string
        index = s.indexOf(replaceThis);
     }
     return original; // same name, different contents.  In C# is valid.
}
于 2013-10-15T00:38:20.943 回答