Question:
How can I get macros from a string, so that they are just what is between [...]
.
Tried this way but it can be broken, is there any 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 it should be: [TESTE][BAR][FOO]
Answer:
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 .