How to organize a search in an array using regular expressions? For example, here’s the code:

var arr = ['земля', 'вода', 'воздух', 'огонь']; $('input').keyup(function(){ var val = $('input').val(); var re = new RegExp(val, 'i'); var result = arr.match(re); return result.input; }); 

How to make the 'fire' permissible when entering, it returns the 'fire'?

  • "He returned the 'fire'" - where did he return it? - Igor
  • Well, I can return anywhere, I need to in 'result.input' what the user enters, but searching in the array is Saul Goodman

1 answer 1

 var arr = ['земля', 'вода', 'воздух', 'огонь']; $('input').keyup(function() { var val = $('input').val().toLowerCase(); var result = arr.filter(item => item.startsWith(val)); console.log(result); if (result.length) { // return result или val куда надо } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input value="ОГонь" /> 

  • As far as I understand, not only one word can come to the input, so you need to put the value of the array in the regular list, and test the shaft, and not vice versa. - MedvedevDev
  • Is it possible that he returns the entire string, for example, he began to introduce 'fire' and in it already 'fire'? val.input not working - Saul Goodman
  • @SaulGoodman What are you so tongue-tied? Do you need to find a string in the array that starts with the string that is entered in the input? ( val is a string. It has no input property.) - Igor
  • Yes, that's right. I need to find a string in the array that starts with the string that was entered in the input, and about the input property, I’m talking about a regular schedule, when you search by the match () method, you end up adding .input so that it outputs the entire string for example var a = 'java'; var result = a.match (/ j / i); alert (result.input) // java and if input is not added, it will output // j - Saul Goodman
  • @SaulGoodman what should be when entered into "in"? - Igor