Javascript 在javascript中,如何在数组中搜索子字符串匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4556099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:55:55  来源:igfitidea点击:

In javascript, how do you search an array for a substring match

javascriptarrayssearch

提问by reub77

I need to search an array in javascript. The search would be for only part of the string to match as the string would have addtional numbers assigned to it. I would then need to return the successfully matched array element with the full string.

我需要在 javascript 中搜索一个数组。搜索将仅匹配字符串的一部分,因为该字符串将分配有附加编号。然后我需要用完整的字符串返回成功匹配的数组元素。

i.e.

IE

var windowArray = new Array ("item","thing","id-3-text","class");

I need to search for the array element with "id-"in it and i need to pull the rest of the text in the element as well (ie. "id-3-text").

我需要在其中搜索数组元素,"id-"并且我还需要提取元素中的其余文本(即。"id-3-text")。

Thanks

谢谢

采纳答案by T.J. Crowder

In your specific case, you can do it just with a boring old counter:

在您的特定情况下,您只需使用一个无聊的旧计数器即可:

var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
    value = windowArray[index];
    if (value.substring(0, 3) === "id-") {
        // You've found it, the full text is in `value`.
        // So you might grab it and break the loop, although
        // really what you do having found it depends on
        // what you need.
        result = value;
        break;
    }
}

// Use `result` here, it will be `undefined` if not found

But if your array is sparse, you can do it more efficiently with a properly-designed for..inloop:

但是,如果您的数组是sparse,您可以使用适当设计的for..in循环更有效地执行此操作:

var key, value, result;
for (key in windowArray) {
    if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
        value = windowArray[key];
        if (value.substring(0, 3) === "id-") {
            // You've found it, the full text is in `value`.
            // So you might grab it and break the loop, although
            // really what you do having found it depends on
            // what you need.
            result = value;
            break;
        }
    }
}

// Use `result` here, it will be `undefined` if not found

Beware naive for..inloops that don't have the hasOwnPropertyand !isNaN(parseInt(key, 10))checks; here's why.

当心for..in没有hasOwnProperty!isNaN(parseInt(key, 10))检查的幼稚循环;这就是为什么



Off-topic:

题外话

Another way to write

另一种写法

var windowArray = new Array ("item","thing","id-3-text","class");

is

var windowArray = ["item","thing","id-3-text","class"];

...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.

...这对你来说打字更少,也许(这一点是主观的)更容易阅读。这两个语句具有完全相同的结果:包含这些内容的新数组。

回答by nickb

If you're able to use Underscore.jsin your project, the _.filter()array function makes this a snap:

如果你能使用Underscore.js在你的项目中,_.filter()阵列的功能,使这个瞬间:

// find all strings in array containing 'thi'
var matches = _.filter(
    [ 'item 1', 'thing', 'id-3-text', 'class' ],
    function( s ) { return s.indexOf( 'thi' ) !== -1; }
);

The iterator function can do whatever you want as long as it returns true for matches. Works great.

迭代器函数可以做任何你想做的事情,只要它为匹配返回 true。效果很好。

Update 2017-12-03:
This is a pretty outdated answer now. Maybe not the most performant option in a large batch, but it can be written a lotmore tersely and use native ES6 Array/String methods like .filter()and .includes()now:

2017-12-03 更新:
现在这是一个非常过时的答案。以大批量的也许不是性能最好的选择,但它可以写成一个很多更简洁,并使用原生ES6数组/字符串的方法,如.filter().includes()现在:

// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));

Note:There's no <= IE11 support for String.prototype.includes()(Edge works, mind you), but you're fine with a polyfill, or just fall back to indexOf().

注意:没有 <= IE11 支持String.prototype.includes()(Edge 工作,请注意),但是您可以使用 polyfill,或者只是回退到indexOf().

回答by nickb

People here are making this waaay too difficult. Just do the following...

这里的人让这件事太难了。只需执行以下操作...

myArray.findIndex(element => element.includes("substring"))

findIndex()is an ES6 higher order method that iterates through the elements of an array and returns the index of the first element that matches some criteria (provided as a function). In this case I used ES6 syntax to declare the higher order function. elementis the parameter of the function (which could be any name) and the fat arrow declares what follows as an anonymous function (which does not need to be wrapped in curly braces unless it takes up more than one line).

findIndex()是一种 ES6 高阶方法,它遍历数组的元素并返回匹配某些条件的第一个元素的索引(作为函数提供)。在这种情况下,我使用 ES6 语法来声明高阶函数。element是函数的参数(可以是任何名称),粗箭头将后面的内容声明为匿名函数(不需要用大括号括起来,除非它占用多于一行)。

Within findIndex()I used the very simple includes()method to check if the current element includes the substring that you want.

在里面,findIndex()我使用了非常简单的includes()方法来检查当前元素是否包含您想要的子字符串。

回答by JonnieJS

Just search for the string in plain old indexOf

只需搜索普通旧字符串 indexOf

arr.forEach(function(a){
    if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
            console.log(a);
    }        
});

回答by smnth90

The simplest way to get the substrings array from the given array is to use filter and includes:

从给定数组中获取子字符串数组的最简单方法是使用 filter 并包括:

myArray.filter(element => element.includes("substring"));

The above one will return substrings array.

上面的将返回子字符串数组。

myArray.find(element => element.includes("substring"));

The above one will return the first result element from the array.

上面的将返回数组中的第一个结果元素。

myArray.findIndex(element => element.includes("substring"));

The above one will return the index of the first result element from the array.

上面的将返回数组中第一个结果元素的索引。

回答by Karthik

The simplest vanilla javascript code to achieve this is

实现这一目标的最简单的香草 javascript 代码是

var windowArray = ["item", "thing", "id-3-text", "class", "3-id-text"];
var textToFind = "id-";

//if you only want to match id- as prefix 
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return (windowValue.substring(0, textToFind.length) === textToFind);
  }
}); //["id-3-text"]

//if you want to match id- string exists at any position
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return windowValue.indexOf(textToFind) >= 0;
  }
}); //["id-3-text", "3-id-text"]

回答by Tgr

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

有关一些替代方案及其效率的有趣检查,请参阅 John Resig 最近的帖子:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

(那里讨论的问题略有不同,干草堆元素是针的前缀,而不是相反,但大多数解决方案都很容易适应。)

回答by Ekim

ref: In javascript, how do you search an array for a substring match

ref: 在javascript中,如何在数组中搜索子字符串匹配

The solution given here is generic unlike the solution 4556343#4556343, which requires a previous parse to identify a string with which to join(), that is not a component of any of the array strings.
Also, in that code /!id-[^!]*/is more correctly, /![^!]*id-[^!]*/to suit the question parameters:

此处给出的解决方案是通用的,与解决方案 4556343#4556343不同,该解决方案需要先前的解析来识别 to 的字符串,该字符串join()不是任何数组字符串的组成部分。
此外,在该代码/!id-[^!]*/中更正确,/![^!]*id-[^!]*/以适应问题参数:

  1. "search an array ..." (of strings or numbers and not functions, arrays, objects, etc.)
  2. "for only part of the string to match " (match can be anywhere)
  3. "return the ... matched ... element" (singular, not ALL, as in "... the ... elementS")
  4. "with the full string" (include the quotes)
  1. “搜索数组...”(字符串或数字,而不是函数、数组、对象等)
  2. “仅匹配字符串的一部分”(匹配可以在任何地方)
  3. “返回 ... 匹配的 ... 元素”(单数,不是全部,如“... ... elementS”)
  4. “带有完整字符串”(包括引号)

... NetScape / FireFox solutions (see below for a JSONsolution):

... NetScape / FireFox 解决方案(有关解决方案,请参见下文JSON):

javascript:         /* "one-liner" statement solution */
   alert(
      ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] .
         toSource() . match( new RegExp( 
            '[^\\]("([^"]|\\")*' + 'id-' + '([^"]|\\")*[^\\]")' ) ) [1]
   );

or

或者

javascript:
   ID = 'id-' ;
   QS = '([^"]|\\")*' ;           /* only strings with escaped double quotes */
   RE = '[^\\]("' +QS+ ID +QS+ '[^\\]")' ;/* escaper of escaper of escaper */
   RE = new RegExp( RE ) ;
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   alert(RA.toSource().match(RE)[1]) ;

displays "x'!x'\"id-2".
Perhaps raiding the array to find ALL matches is 'cleaner'.

显示"x'!x'\"id-2".
也许突袭阵列以找到所有匹配项是“更干净”的。

/* literally (? backslash star escape quotes it!) not true, it has this one v  */
javascript:                            /* purely functional - it has no ... =! */
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   function findInRA(ra,id){
      ra.unshift(void 0) ;                                     /* cheat the [" */
      return ra . toSource() . match( new RegExp(
             '[^\\]"' + '([^"]|\\")*' + id + '([^"]|\\")*' + '[^\\]"' ,
             'g' ) ) ;
   }
   alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;

displays:

显示:

     "x'!x'\"id-2"

     "' \"id-1 \""

     "id-3-text"

Using, JSON.stringify():

使用,JSON.stringify()

javascript:                             /* needs prefix cleaning */
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   function findInRA(ra,id){
      return JSON.stringify( ra ) . match( new RegExp(
             '[^\\]"([^"]|\\")*' + id + '([^"]|\\")*[^\\]"' ,
             'g' ) ) ;
   }
   alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;

displays:

显示:

    ["x'!x'\"id-2"

    ,"' \"id-1 \""

    ,"id-3-text"

wrinkles:

皱纹:

  • The "unescaped" global RegExp is /[^\]"([^"]|\")*id-([^"]|\")*[^\]"/gwith the \to be found literally. In order for ([^"]|\")*to match strings with all "'s escaped as \", the \itself must be escaped as ([^"]|\\")*. When this is referenced as a string to be concatenated with id-, each \must again be escaped, hence ([^"]|\\\\")*!
  • A search IDthat has a \, *, ", ..., must also be escaped via .toSource()or JSONor ... .
  • nullsearch results should return ''(or ""as in an EMPTY string which contains NO "!) or [](for all search).
  • If the search results are to be incorporated into the program code for further processing, then eval()is necessary, like eval('['+findInRA(RA,ID).join(',')+']').
  • 该“转义”全局RegExp是/[^\]"([^"]|\")*id-([^"]|\")*[^\]"/g\从字面上找到。为了([^"]|\")*匹配所有"转义为 as 的字符串\"\本身必须转义为([^"]|\\")*。当 this 被引用为要与 连接的字符串时id-,每个都\必须再次转义,因此([^"]|\\\\")*!
  • ID具有\, *, ", ... 的搜索也必须通过.toSource()orJSON或 ...进行转义。
  • null搜索结果应返回''(或""在包含 NO 的 EMPTY 字符串中"!)或[](对于所有搜索)。
  • 如果要将搜索结果合并到程序代码中以供进一步处理,则eval()是必要的,例如eval('['+findInRA(RA,ID).join(',')+']')

--------------------------------------------------------------------------------

-------------------------------------------------- ------------------------------

Digression:
Raids and escapes? Is this code conflicted?
The semiotics, syntax and semantics of /* it has no ... =! */emphatically elucidates the escaping of quoted literals conflict.

题外话:
突袭和逃跑?这段代码有冲突吗?
的符号学、句法和语义学/* it has no ... =! */着重阐明了引用文字冲突的逃避。

Does "no =" mean:

“否=”是指:

  • "no '=' sign" as in javascript:alert('\x3D')(Not! Run it and see that there is!),
  • "no javascript statement with the assignment operator",
  • "no equal" as in "nothing identical in any other code" (previous code solutions demonstrate there are functional equivalents),
  • ...
  • "no '=' sign" as in javascript:alert('\x3D')(不是!运行它,看看有!),
  • “没有带有赋值运算符的 javascript 语句”,
  • “不等于”如“在任何其他代码中都不相同”(以前的代码解决方案表明存在功能等效项),
  • ...

Quoting on another level can also be done with the immediate mode javascript protocol URI's below. (// commentaries end on a new line (aka nl, ctrl-J, LineFeed, ASCII decimal 10, octal 12, hex A) which requires quoting since inserting a nl, by pressing the Return key, invokes the URI.)

另一个级别的引用也可以使用下面的立即模式 javascript 协议 URI 来完成。(// 评论以新行结束(又名 nl、ctrl-J、LineFeed、ASCII 十进制 10、八进制 12、十六进制 A),自从插入 nl 后需要引用,按 Return 键调用 URI。)

javascript:/* a comment */  alert('visible')                                ;
javascript:// a comment ;   alert(  'not'  ) this is all comment             %0A;
javascript:// a comment %0A alert('visible but  %
let url = item.product_image_urls.filter(arr=>arr.match("homepage")!==null)
A is wrong ') // X %0A javascript:// a comment %0A alert('visible but %'+'0A is a pain to type') ;

Note: Cut and paste any of the javascript:lines as an immediate mode URI (at least, at most?, in FireFox) to use first javascript:as a URI scheme or protocol and the rest as JS labels.

注意:剪切并粘贴任何javascript:行作为立即模式 URI(至少,至多?,在 FireFox 中),首先javascript:用作 URI 方案或协议,其余用作 JS 标签。

回答by Biswajit

var array = ["page1","1973","Jimmy"]; 

Filter array with string match. It is easy and one line code.

使用字符串匹配过滤数组。这是简单的一行代码。

回答by Andrew Sainsbury

I think this may help you. I had a similar issue. If your array looks like this:

我想这可能对你有帮助。我有一个类似的问题。如果您的数组如下所示:

var c; 
for (i = 0; i < array.length; i++) {
if (array[i].indexOf("page") > -1){ 
c = i;}
} 

You can do a simple "for" loop to return the instance in the array when you get a match.

您可以执行一个简单的“for”循环以在获得匹配项时返回数组中的实例。

##代码##

We create an empty variable, c to host our answer. We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)

我们创建一个空变量 c 来承载我们的答案。然后我们遍历数组以找到数组对象(例如“page1”)与我们的indexOf(“page”)匹配的位置。在这种情况下,它是 0(第一个结果)

Happy to expand if you need further support.

如果您需要进一步的支持,很高兴扩展。