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?
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.
Extending the contains function you linked to:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
if(a[i].search(regex) > -1){
return i;
}
}
return -1;
}
Then you call the function with an array of strings and a regex, in your case to look for height:
containsRegex([ '<param name="bgcolor" value="#FFFFFF" />', 'sdafkdf' ], /height/)
You could additionally also return the index where height was found:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
int pos = a[i].search(regex);
if(pos > -1){
return [i, pos];
}
}
return null;
}
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);
链接地址: http://www.djcxy.com/p/74950.html
上一篇: 是否有更好的方法来搜索JavaScript数组而不是使用jQuery的每一个?
下一篇: 如何搜索字符串数组中的字符串