Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Performing multiple replaces in iteration

Last post 07-23-2012, 9:36 PM by Aussie Susan. 1 replies.
Sort Posts: Previous Next
  •  07-23-2012, 2:57 PM 85850

    Performing multiple replaces in iteration

    I'm working with JS on Kettle and am trying to create logic which will search regex patterns and enclose these captured strings in parentheses for one to many occurrences. For example, in the string 'ABCDABCABD' the desired result would be '(AB)CD(AB)C(AB)D' with a regex of /AB/g.

    I have tried using this logic without any success because it ends up in a loop replacing the first occurrence over and over. From google searchs, I was under the assumption that lastIndex would set the starting point for the next iteration but that is not happening.

     var src = "ABCDABCABD";
     var arr;
     var re = /AB/g;
        
    while ( (arr = re.exec(src)) != null)
       { src = src.replace(arr[0], "(" + arr[0] + ")" );
     
       }

    Can someone please offer a suggestion on how to handle situations like this?

    TIA

    Gerald

  •  07-23-2012, 9:36 PM 85852 in reply to 85850

    Re: Performing multiple replaces in iteration

    From what I understand about the JavaScript regex functions, the "replace()" function can take either a string (as you are passing) or a regex pattern.

    I *think* what you want to use is:

    src = src.replace(/ab/g, "($0)");

    The "/g" tells the regex engine to perform a "G"lobal replace which means that it will do the iterations for you. Also the '$0' is a back-reference to the entire matched text - in effect the same as the 'arr[0]' i your program.

    I don't know enough about the JavaScript regex functions specifically, but I do know that there is no such thing as a "common" regex in terms of pattern syntax or capabilities of the regex engine. I suspect that the "last index" that you were referring to IS used by some regex implementations to let the user define a starting point (the .NET regex replace() function has a version with 4 parameters, the last one being where to start the search in the text string) and there are all sorts of ways that this is implemented. However the regex engine used in JavaScript seems to be fairly limited in its capabilities (in this regard at least) and therefore you need to use the technique I mentioned above.

    Susan

View as RSS news feed in XML