2010-06-21 86 views
3

我想與RegEx一起使用來將大字符串拆分爲更小的部分,並且作爲此部分的一部分,我試圖在此替換所有子字符串的實例大字符串。我一直在嘗試使用替換函數,但這隻會替換子字符串的第一個實例。我怎樣才能在更大的字符串中替換子字符串的al實例?如何替換字符串中的子字符串的所有實例

感謝

斯蒂芬

回答

10

加入'g'到searchExp。例如/i_want_to_be_replaced/g

+0

不要忘記,正則表達式是不是內 「」。 (我犯了這個錯誤) – csomakk 2013-11-20 10:08:07

3

的一個快速方法是使用分割和結合​​:

function quickReplace(source:String, oldString:String, newString:String):String 
{ 
    return source.split(oldString).join(newString); 
} 
0

除了@亞歷克斯的答案,您也可以使用字符串的方法replace()找到this answer得心應手, 。

這裏有一個片段:

function addLinks(pattern:RegExp,text:String):String{ 
    var result = ''; 
    while(pattern.test(text)) result = text.replace(pattern, "<font color=\"#0000dd\"><a href=\"$&\">$&</a></font>"); 
    if(result == '') result+= text;//if there was nothing to replace 
    return result; 
} 
相關問題