繁体   English   中英

替换字符串中的多次出现

[英]replace multiple occurrence in string

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

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

我用string.replace代替了所有的出现,但是我还是想要最后一个。

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

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"

一种略有不同的方法,同时支持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);

不管使用哪种语言,都没有内置方法可以做到这一点。 您可以做的事情类似(可能需要调试)

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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM