IF-ELSE problems

Asked

Viewed 132 times

1

I have the following code, to find a certain numbering and check if it exists. STR variable sends text with numbers.

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 may be wrong ?

  • He is probably respecting, but the rules are not the ones that would give the result you expect. Could for a practical example how the problem manifests itself?

1 answer

4


You have two problems with your code.

The first problem is that when you want to compare two variables you have to use the ==, or ===. What you use is an assignment =, and this does not compare anything. Using only = will make the variable on the left turn the value on the right. Actually when you use = is rewriting the function .match(). That is, the .match() becomes the value I assign to it and ceases to function...

The second problem is the way to use the .match(). I assume you want to use the if in the case of str have a certain character set. Then you only need to use something like str.match(/[1-2]/). This alone 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/)) {

Once you want to assign 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
}
  • I thought I’d "fix" it for exactamente, but I think you’re abrasing your Portuguese, entonces didn’t move ;)

  • 1

    @brasofilo haha :) This emigrate to Sweden and participate here where the majority is Brazilian in their side effects :)

  • Perfect reply @Sergio, thank you!

  • @Sergio, taking advantage of the question, do you know how I can detect line breaks in the string ? Example: (/ d d d d d d d d/ ) After "." has a ENTER..?

  • @user7605 \n can be used for new lines.

  • @Sergio, in case I would use it like this: / d d d d d d n. d d d d d d d d d d d d d d d d/ ?

Show 1 more comment

Browser other questions tagged

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