Problems IF-ELSE

1

I have the following code, to look up a certain numbering and check if it exists. In the STR variable, text with numbers is sent.

function verifica(str) {
if (str.match = '/\d\d\d\d\d\.\d\d\d\d\d')  {
    var old = str.match(/\d\d\d\d\d\.\d\d\d\d\d/);
    result = 1;
}

else if (str.match = '/\d\d\d\d\d\.\d\d\d')  {
    var old = str.match(/\d\d\d\d\d\.\d\d\d/);
    result = 2;

} }

He is not respecting these rules, he only respects the if, the else IF does not respect. What could be wrong?

    
asked by anonymous 25.05.2014 / 05:46

1 answer

4

There are two problems with your code.

The first problem is that when you want to compare two variables you must use == , or === . What you use is a = assignment, and this compares nothing. Using only = will make the left variable stay with the value that is on the right. Actually when using = you are rewriting the .match() function. That is, .match() is assigned the value that it assigns and stops working ...

The second problem is how to use .match() . I assume you want to use if in case str has a certain set of characters. Then just use something like str.match(/[1-2]/) . This in itself already returns what you need to use in if. For example:

var str = '1233';
str.match(/[1-2]/);   // dá verdadeiro no if, mais exatamente ["1"]
str.match(/[1-2]/g);  // dá verdadeiro, mais exatamente ["1", "2"] pois usa o "g" no match que retorna não só o primeiro encontrado

So what you should use is only:

if (str.match(/\d\d\d\d\d\.\d\d\d\d\d/)) {

Since you want to assign a new value to the variable old , and remembering that an attribute with = returns a value if you do not use var then your code could be :

function verifica(str) {
    var old;
    if (old = str.match(/\d\d\d\d\d\.\d\d\d\d\d/)) {
        result = 1;
    } else if (old = str.match(/\d\d\d\d\d\.\d\d\d/)) {
        result = 2;
    }
    return result; // isto acrescentei eu, para a função retornar um valor
}
    
25.05.2014 / 09:08