替换字符串中的多个匹配项

时间:2013-10-15 00:25:53

标签: javascript node.js

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

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

我使用string.replace替换所有出现,但我仍然想要最后一个。如果它是天真的那么

3 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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);

答案 2 :(得分: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.
}