How to Catch Variable Macros in a String

Asked

Viewed 35 times

3

How can I take macros from a string, so that they are just what you have between [...].

I tried this way, but it can be broken, has some way of doing 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 exit is: [TESTE][você recebe sms, [BAR][FOO] but it should be: [TESTE][BAR][FOO]

2 answers

1


You can use the 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.

What about the match here.

0

Browser other questions tagged

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