2013-10-15 55 views
-1

我想替換多個匹配項中特定單詞的匹配項並僅保留最後一個。替換字符串中的多個匹配項

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

我用與string.replace全部更換出現時但我還是想最後one.sorry如果是天真

+0

你能找到的最後一個表達式的索引,然後將它移動到它自己的字符串中,然後執行替換,然後將字符串重新排列在一起。 – ermagana

回答

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" 
+0

謝謝!很棒。深深地感謝 –

+0

@JackDre在_stackoverflow_上有一些有用的東西時,不要忘記註冊它。然後,如果答案解決了您的問題,請不要忘記將其標記爲解決方案。 –

+0

我試過了,我現在只有14人,現在只有一人downvoted :)一旦我把它拿回來,我會upvote。 –

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

謝謝。讚賞。 –

1

稍微不同的方法,同時支持正則表達式和普通字符串針:

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);