3

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

StephenAdams
  • 521
  • 2
  • 9
  • 26

3 Answers3

10

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

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Alex Zharnasek
  • 519
  • 5
  • 9
3

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
  • 40,306
  • 11
  • 38
  • 43
0

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;
}
Community
  • 1
  • 1
George Profenza
  • 50,687
  • 19
  • 144
  • 218