Search code examples
angularjsstringstr-replacereplaceall

If an occurance is more than two times contiunously replace that occurance with a new word angularjs


I have a text coming from backend with multiple breaks coming 2 breaks, 4 breaks or 6 breaks and i want to replace breaks with 2 breaks. For eg: if in a string i have four continuous breaks, then I want to replace those breaks with 2 breaks only.

I tried following code, but didn't worked:

TMSApp.filter('newlinesmatch', function () {
    return function(text) {
        var str = '<br>';
        var count = (text.match(/<br>/g) || []).length;
        if(count > 2){
            return String(text).replace(/<br>/g,'<br><br>');    
        }
    }
});

can some one help?


Solution

  • You can replace any number of consecutive occurrences of <br> with <br><br> like this:

    TMSApp.filter('newlinesmatch', function () {
        return function(text) {
            return text.replace(/(<br>)+/g, '<br><br>');
        }
    });
    

    NOTE: I know you mentioned that you will always be getting 2, 4, or 6 consecutive breaks. However, it is worth noting that the solution above would replace any number of consecutive occurrences (even a single one) with <br><br>.

    EDIT:

    Per the comment below with a REAL example, I have made the change below. Note that the original answer works for the originally described scenario, where the need was to replace CONSECUTIVE <br>s. The REAL example does not have consecutive <br>s since there is a space between every pair. The following code will work for that case:

    .filter('newlinesmatch', function () {
        return function(text) {
          return text.replace(/(<br>\s*)+/g, '<br><br>');
        }
    });
    

    And here is a working plunker with the sample data provided:

    http://plnkr.co/edit/ztcsbJoJ51ZF8FcJylbC?p=preview