Skip to content Skip to sidebar Skip to footer

How Do I Loop Through A Regex's Matches Inside A Replace In Javascript?

I have the following JavaScript (the spaces in the

s are non-breaking): var html = '...

  • sub 2
  • \n\

     &a

    Solution 1:

    Here's the solution that I came up with but it doesn't seem to be very efficient:

    $(function () {
        var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:<ol(?:\sstyle=\"[^\"]+\")?\sstart=\"[^\"]+\">\s*)+/gi;
        var nestedListItem = /<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*/gi;
    
        // fix nested lists
        html = html.replace(nestedListFixer, function($0, $1){
            var lis = ""
            $.each($0.match(nestedListItem), function () {
                lis += "<li>" + this.replace(nestedListItem, "$1") + "</li>\n";
            });
            return"<ol>\n" + lis + "</ol></li>";
        });
    });
    

    ...or for the simpler example above:

    $(function () {
        var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/gi;
        var textItem = /b(.*?)c/gi;
    
        text = text.replace(textFixer, function($0, $1){
            var numbers = "";
            $.each($0.match(textItem), function () {
                numbers += this.replace(textItem, "$1");
            });
            return numbers;
        });
    });
    

    Doing a .replace() substitution, inside a loop of a .match() array, inside of a custom .replace() function just doesn't seem like it is very economical. It does give me the output that I was looking for though.

    Solution 2:

    A pretty loop can be using hook pattern :

    var text = '1ab2cb3cd4ab5cb6cd7';
    text.match(/(\d)/g).forEach(function(element,index){
       console.log(element)
    });
    

    Post a Comment for "How Do I Loop Through A Regex's Matches Inside A Replace In Javascript?"