Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a string inside an array of strings

After searching for an answer in other posts, I felt I have to ask this. I looked at How do I check if an array includes an object in JavaScript? and Best way to find if an item is in a JavaScript array? and couldn't get the code there to work.

I am capturing an html embed code into an array, so each item is a line of html code.

for example:

i[0]='<param name=\"bgcolor\" value=\"#FFFFFF\" />' i[1]='<param name=\"width" value=\"640\" />' i[2]='<param name=\"height\" value=\"360\" />'    i[3]='more html code'  

I want to search this array and find the line where the word 'height' is.

So ideally, I'd like to write a function that returns the index of the item where 'height' appears.

Fortunately, there are no duplicates in this array, so there's only one occurrence.

with simple object search I get 'false' returns.

Any idea?

like image 657
someuser Avatar asked Mar 24 '11 19:03

someuser


People also ask

How do I find a string in an array of strings?

Use Linq Contains() method to search for as specific string in an array of strings. string[] arr = { "Bag", "Pen", "Pencil"}; Now, add the string in a string variable i.e. the string you want to search.

How do you search inside an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


2 Answers

It's as simple as iterating the array and looking for the regexp

function searchStringInArray (str, strArray) {     for (var j=0; j<strArray.length; j++) {         if (strArray[j].match(str)) return j;     }     return -1; } 

Edit - make str as an argument to function.

like image 61
Aleadam Avatar answered Oct 05 '22 23:10

Aleadam


You can use Array.prototype.find function in javascript. Array find MDN.

So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.

Ex.

var strs = ['abc', 'def', 'ghi', 'jkl', 'mno']; var value = 'abc'; strs.find(     function(str) {         return str == value;     } ); 

or using lambda expression it will become much shorter

var strs = ['abc', 'def', 'ghi', 'jkl', 'mno']; var value = 'abc'; strs.find((str) => str === value); 
like image 45
Chetan Khilosiya Avatar answered Oct 06 '22 00:10

Chetan Khilosiya