Uncaught Syntaxerror: Unexpected token var

Asked

Viewed 302 times

0

I’m doing a simple test with Regexp on Jsfiddle and I don’t understand why

Uncaught Syntaxerror: Unexpected token var

Look at: http://jsfiddle.net/cbLs8/

Code:

<input type="text" id="entrada"></input>
<button id="botao">Testar</button>

$("#botao").click(function () {
    if (var m = $("#entrada").val().match(/\d-\d/g)) {
        for (var i = 0; i < m.length(); i++) {
            alert(m[i]);
        }
    } else {
        alert("no match");
    }
});

Update

After @Sergio’s suggestion I’m having another mistake:

Uncaught Typeerror: number is not a Function

On that line here: for (i = 0; i < m.length(); i++) {

Jsfiddle updated: http://jsfiddle.net/cbLs8/1/

1 answer

2


Cannot define variables within a if(), the reason for this not being possible is that a variable definition always returns undefined and then your if would always fail.

Use like this:

$("#botao").click(function () {
    var m; // defina a variável fora do if para estar defenida e não exportar para o espaço global
    if (m = $("#entrada").val().match(/\d-\d/g)) {
  • Regarding this is now working, but now I have another error. I edited my question.

  • 1

    I just put a line before, like in the if. If I leave the way I was before it’s the same mistake.

  • @Andrey, THE .match gives you an array but only with one element. What exactly do you want to do? Want to make Alert of all intermediate numbers? can explain better?

  • Exactly. I wanted to identify all the occurrences of número-número. The match don’t call me back at all all the occurrences?

  • 1

    @Andrey your problem is that length is a property, not a function. You should use .length only.

  • 1

    Solved now! Thank you Sergio.

  • 1

    @Andrey, by the way: http://jsfiddle.net/LvuEs/

  • My doubt was the same mistakes. The regular expression I intend to change, I’m doing tests.

Show 3 more comments

Browser other questions tagged

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