How to get varying macros in a string

3

How can I get the macros of a string, so that they are only what you have between [...] .

I tried this way, but it can be broken, have some way to do it using regular expressions?

var texto = "HIGHLANDER esse aqui [TESTE] muito massa pra ver se [você recebe sms, [BAR] desconsidere ai, valeu! [FOO]";

var tamanhoDoTexto = texto.length;
var arrayMacros = [];
var abriu = false;

for (var i = 0; i < tamanhoDoTexto; i++) {

  if (texto[i] == "[") {
    abriu = true;
    arrayMacros.push(texto[i]);
  } else if (texto[i] == "]") {
    abriu = false;
    arrayMacros.push(texto[i]);
  } else if (abriu) {
    arrayMacros.push(texto[i]);
  }
}

console.log(arrayMacros.join(""));

The output is: [TESTE][você recebe sms, [BAR][FOO] but should be: [TESTE][BAR][FOO]

    
asked by anonymous 11.04.2017 / 14:32

2 answers

1

You can use match to do this:

var text = "HIGHLANDER esse aqui [TESTE] muito massa pra ver se [você recebe sms, [BAR] desconsidere ai, valeu! [FOO]";

var result = text.match(/\[\w+\]/g);

console.log(result.join(''));

Read more about regex here .

And about the match here .

    
11.04.2017 / 15:02
0

You can use regex.match

Follow the example in jsfiddle: link

    
11.04.2017 / 15:01