1

Apologies if this is a duplicate, but I can't seem to find the solution. I am trying to find a specific string pattern in an array. I want to find all values in data that contain 'underscore r underscore'. I then want to create a new array that contains only those keys and values.

var data = ["something", "bar_r_something"];
var resultArray = new Array();    
for (var i = 0; i < data.length; i++) {
    var bar = /_r_/;
    if ($.inArray(bar, data[i].length) > 0)
    {
       console.log("found _r_");
       resultArray.push(data[i]);
    }
};

I just can't seem to get that $.inArray to work, it seems to always kick out -1.

1

2 Answers 2

5
var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
    var bar = /_r_/;
    if (bar.test(data[i])) {
        alert("found _r_");
        resultArray.push(data[i]);
    }
};

console.log(resultArray);

Here you go, it doesn't use $.inArray, but Regex instead, hope that's cool!

EDIT

If you wanted to go a bit more fancy, you can use JavaScript's filter method like so:

var data = ["something", "bar_r_something"];
var resultArray = data.filter(function(d){
    return /_r_/.test(d);
});

console.log(resultArray);
Sign up to request clarification or add additional context in comments.

Comments

2

I think what you are looking for is $.grep(). Also $.inArray() does not test the values against a regex, it tests for equality.

var regex = /_r_/
var resultArray  = $.grep(data, function(item){
    return regex.test(item)
})

Demo: Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.