[英]Is there a javascript method to find substring in an array of strings?
Suppose my array is ["abcdefg", "hijklmnop"] and I am looking at if "mnop" is part of this array. 假设我的数组是[“ abcdefg”,“ hijklmnop”],并且我正在查看“ mnop”是否是该数组的一部分。 How can I do this using a javascript method?
如何使用javascript方法做到这一点?
I tried this and it does not work: 我试过了,它不起作用:
var array= ["abcdefg", "hijklmnop"];
console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
var array= ["abcdefg", "hijklmnop"];
var newArray = array.filter(function(val) {
return val.indexOf("mnop") !== -1
})
console.log(newArray)
a possible solution is filtering the array through string.match
一个可能的解决方案是通过
string.match
过滤数组
var array= ["abcdefg", "hijklmnop"]; var res = array.filter(x => x.match(/mnop/)); console.log(res)
You can use Array#some
: 您可以使用
Array#some
:
// ES2016
array.some(x => x.includes(testString));
// ES5
array.some(function (x) {
return x.indexOf(testString) !== -1;
});
Note: arrow functions are part of ES6/ES2015; 注意:箭头功能是ES6 / ES2015的一部分;
String#includes
is part of ES2016. String#includes
是ES2016的一部分。
The Array#some
method executes a function against each item in the array: if the function returns a truthy value for at least one item, then Array#some
returns true. Array#some
方法对数组中的每个项目执行一个函数:如果该函数返回至少一项的真实值 ,则Array#some
返回true。
Javascript does not provide what you're asking before because it's easily done with existing functions. Javascript无法提供您之前要问的内容,因为使用现有功能很容易做到。 You should iterate through each array element individually and call
indexOf
on each element: 您应该分别遍历每个数组元素,并在每个元素上调用
indexOf
:
array.forEach(function(str){
if(str.indexOf("mnop") !== -1) return str.indexOf("mnop");
});
Can be done like this https://jsfiddle.net/uft4vaoc/4/ 可以这样https://jsfiddle.net/uft4vaoc/4/
Ultimately, you can do it a thousand different ways. 最终,您可以用一千种不同的方式来做。 Almost all answers above and below will work.
上面和下面的几乎所有答案都将起作用。
<script>
var n;
var str;
var array= ["abcdefg", "hijklmnop"];
//console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
for (i = 0; i < array.length; i++) {
str = array[i];
n = str.includes("mnop");
if(n === true){alert("this string "+str+" conatians mnop");}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.