How to replace all substring instances in a string

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

thank

Stephen

+3
source share
3 answers

add 'g'to searchExp. eg/i_want_to_be_replaced/g

+10
source

One quick way is to use split and join:

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

@Alex , String replace().

:

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

Source: https://habr.com/ru/post/1751033/


All Articles