StephenAdams
StephenAdams

Reputation: 529

how to replace all instances of a sub string in a string

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

Upvotes: 3

Views: 3425

Answers (3)

Alex Zharnasek
Alex Zharnasek

Reputation: 519

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

Upvotes: 10

George Profenza
George Profenza

Reputation: 51847

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

Upvotes: 0

James Fassett
James Fassett

Reputation: 41064

One fast way is use split and join:

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

Upvotes: 3

Related Questions