G
G
Grayni Web2017-10-11 03:26:36
JavaScript
Grayni Web, 2017-10-11 03:26:36

Why is the variable outside of the keyup event handler checked once?

There is a form for entering a link. We check in real time that the user started to write a link from http:// or https://. I set hyper = RegExp to the variable and substituted it into the condition via test(), which is located in the keyup handler function.
For clarity, an individual element will change color to green if true and to red if false.
The question is.
If the variable is declared inside the handler function, then everything is fine. Those. when we entered http:// , then the next block is always green, but I need a global variable, because you need to substitute the same variable in another handler and somehow it will not be beautiful if you multiply it.
And the global one starts "blinking" when we enter http:// and continue typing. Explain this behavior and advise how to turn it around so that it works normally with a global variable.

View here: Click me

<div class="card-body">
  <form action="">
  <input tyle='text' id='long-link' name="link">
  </form>
</div>

var long = $('#long-link'), hyper = new RegExp ('^https://|^http://','g');
  long.keyup(function(){
    if (hyper.test(long.val()))  {
      $('.card-body').css({'background':'#4cfa76'});
    }
    else $('.card-body').css({'background':'#af1d1d'});
  });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-10-11
@Grayni

Explain this behavior

You have declared a regular expression with a modifier g- that is, all matches are searched for the pattern, not just the first one. You call the test method - a match is found, cool. You call again - the search does not start from the beginning, but from the place where it ended last time. Of course, nothing was found this time. You call test a third time - everything is fine again, because the last time there were no matches, the search is again performed from the beginning of the string.
please advise how to turn it out so that it works normally

1. Remove modifier g.
2. After each call to test, manually reset the position from which to start searching for a match with the pattern: . Of course, this option is govnokodom. hyper.lastIndex = 0;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question