How to loop with regex in javascript?

3

Hello everyone, how are you? I'm breaking my head on the following question:

I have a string set:

var teste = blabla 555..  999

I have double white space between the digits and did the regex:

var str = teste.replace(/\s{2,}/g, '.');

The problem that it will replace the two spaces by just a "." point, I wanted to loop with the following algorithm:

  • I found 2 blanks
  • Replace with colon. ""
  • It would look like this: test = blabla 555 .... 999
  • Some light, path of stones?

        
    asked by anonymous 09.08.2014 / 05:19

    2 answers

    2

    I'm not a guru in JavaScript, so any error is just saying.

    function times(str, n){
        var step = str;
        for (var y = 1; y < n; y++){
           str = str.concat(step);
        }
        return str;
    }
    
    test = "a b  d"
    test = test.replace(/\s{2,}/g, function(match) {
        return times(".", match.length);
    });
    
    >>> a b..d
    

    Test: JSFiddle

    It finds sequences of spaces n ≥ 2 and makes replace by '.' * n .

        
    09.08.2014 / 07:50
    2

    I do not know if I understand, your problem.

    But if I understand you want to search in a certain phrase two blank spaces followed and replace them with ".."? Right?

    If so, you only need to change replace like this:

    // procura por 2 espaços em branco da frase e substitui por ".."
    var str = teste.replace(/\s{2,}/g, '..');
    

    Example online.

    Check if this is what you needed?

        
    09.08.2014 / 06:15