views:

56

answers:

3

Hi,

I'm trying to work with RegEx to split a large string into smaller sections, and as part of this I'm trying to replace all instances of a substring in this larger string. I've been trying to use the replace function but this only replaces the first instance of the substring. How can I replace al instances of the substring within the larger string?

Thanks

Stephen

+7  A: 

adding 'g' to searchExp. e.g. /i_want_to_be_replaced/g

Alex
A: 

One fast way is use split and join:

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

In addition to @Alex's answer, you might also find this answer handy, using String's replace() method.

here's a snippet:

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;
}
George Profenza