Function jQuery match, how to get the matches

1

How can I get matches using the match function?

console.log($("COMMANDO database -> run []").match(/COMMAND\S*(.*)\S*->\S*(.*)/g)[0]);

In theory I would have to get database , run and what's inside []

    
asked by anonymous 23.12.2014 / 15:05

2 answers

5

The Match method is not from JQuery, it is native of the Javascript language, I modified its regular expression to get the content inside the brackets.

var regex = /\S*(.*)\S*->\S*(.*)\[(.*?)\]/i; 
var input = "COMMANDO database -> run [conteúdo]"; 
if(regex.test(input)) {
  var matches = input.match(regex);
  for(i = 0; i < matches.length; i++){
        alert(matches[i]);
    }
} else {
  alert("Nenhuma combinação encontrada.");
}
    
23.12.2014 / 15:10
1

There is no function match in the jQuery library. You may want to use the String.match native javascript function. It works like this:

"COMMANDO database -> run []".match(/COMMAND\S*(.*)\S*->\S*(.*)/)

Notice that you had to remove the g flag from the regex to capture groups. Note also that the string contains COMMANDO while regex looks for COMMAND . In this case, there is no match.

    
23.12.2014 / 15:15