Search code examples
javascriptarraysmatchingstring-matchingregexp-substr

How to use regex match in string array?


I want to this : When the entered value matches the value of the my array , write the matches value.

so this is my code :

//my array as the following :

var checkNames = (document.getElementById("KPIorCounterList").value.split("\n").map(element => element.trim())).filter(v=>v != "");

my another array : myarray= ["RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"]

For example ; when write RAB* to textare, I should to see, starting with "RAB"

I guess, My code should be as follows:

  for (var i = 0; i < checkNames.length; i++) {
                    for (var j = 0; j < myarray.length; j++) {
           // var str = myarray[j].split(" "); // I am not sure for his.

            I want to this for here : (pseudo code)
            for example checkName[i] == RAB*
            if (checkName[i].match("match condition") == myarray[j])
            alert(myarray[j]);
            //I should show output myarray[j] == RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"
       }
    }

How can I do ? Please..


Solution

  • function check(){
    var checkNames = (document.getElementById("KPIorCounterList").value.split("\n").map(element => element.trim())).filter(v=>v != "");
    var myarray = ["RAB Video call drop %", "RAB PS R99 drop % ", "RAB PS HSDPA drop %"]
    for (var i = 0; i < checkNames.length; i++) {
      console.log("results for", checkNames[i])
      for (var j = 0; j < myarray.length; j++) {
    
          var matchString = myarray[j].match(new RegExp(checkNames[i].replace('*','.*')));
        if (matchString && myarray.indexOf(matchString[0])!==-1) {
          console.log(myarray[j]);
        }
        //I should show output myarray[j] == RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"
      }
    }
      }
    <textarea id="KPIorCounterList"></textarea>
    <button onclick="check()">Check</button>