How to loop with regex in javascript?

Asked

Viewed 125 times

3

Hello everybody all right? I’m cracking 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 only one point ".", I wanted to make a loop with the following algorithm:

  1. I found 2 blank spaces
  2. Replaced by two points "."
  3. It would look like this: test = Blabla 555.... 999

Some light, path of stones?

  • Try to do /\s{1}/g, and replace each space by a point, using a while.

2 answers

2

I’m not sure I understand, your problem.

But if I understand you want to search a given sentence for two blank spaces in a row and replace them with ".."? Right?

If so, just change the replace thus:

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

Online example.

Make sure that’s what you needed?

  • Hello Fernando, the dxhj solution worked. Thank you for your answer. Hugs.

2


I’m not a Javascript guru, so any mistake is just to say.

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

Testing: Jsfiddle

Find sequences of spaces n ≥ 2 and does due replace for '.' * n.

  • 1

    Hello dxhj, it worked perfectly. Thank you very much. I will take the table test to understand the algorithm. I always like to know how things work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.