如何在字符串数组中搜索字符串 [英] How to search for a string inside an array of strings

查看:80
本文介绍了如何在字符串数组中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他帖子中寻找答案后,我觉得我必须问这个.我查看了 如何检查数组是否包含 JavaScript 中的对象?查找项目是否在 JavaScript 中的最佳方法数组?并且无法让代码在那里工作.

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.

我正在捕获一个 html 嵌入代码到一个数组中,所以每个项目都是一行 html 代码.

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

例如:

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' 

我想搜索这个数组并找到'height'这个词所在的行.

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.

通过简单的对象搜索,我得到 'false' 回报.

with simple object search I get 'false' returns.

有什么想法吗?

推荐答案

就像迭代数组并寻找正则表达式一样简单

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;
}

编辑 - 将 str 作为函数的参数.

Edit - make str as an argument to function.

这篇关于如何在字符串数组中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆