Home > front end >  search text in array using regex in javascript
search text in array using regex in javascript

Time:07-03

I am very new to making search text in array some elements in array are in rangers i.e it cant be anything after certain text in this AA and A regex and I have multi-dimensional array and I want search text in each array . So I wrote something like this.I put AA* in array so only first 2 character should match and A* for only one character match.

arr = [
     ["AA*","ABC","XYZ"] ,
    ["A*","AXY","AAJ"]
    ]
    var text = "AA3";
    for ($i=0; $i<arr.length; $i   ){
        var new_array = [];
        new_array = arr[$i];
        new_array.filter(function(array_element) {
              var result = new RegExp(array_element).test(text);
              
              if( result == true){
                console.log(arr[$i]);
          } 
            
          });
    }

So what i want is when text = "AA3" or anything after double A AA[anything] and the output should be first array which is ["AA*","ABC","XYZ"] but I am getting both array as output and when text = "A3" then output should be second array which is ["A*","POI","LKJ"] but I am getting both array.But if text = "ABC" or text = "AAJ" then it should output first array or second array respectively.I dont know anything about how to write regex or is there anyway I can implement this using any other method. Thanks in advance any advice will be helpful.

CodePudding user response:

Summary

In short, the issue is "*"! The * found in the members of the set array is why you're getting the same array each time.

Detailed Info

Regexp is a one concept most developers find hard to understand (I am one of such btw

  • Related