非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。
当前回答
对于用谷歌搜索的人来说,
确切的答案应该是。
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
其他回答
单线解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
如果子字符串存在\不存在,则返回true\false
需要ES6支持
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
以下是目前为止(在我看来)最好的解决方案。这是一个现代的(ES6)解决方案,它:
是高效的(一行!) 避免for循环 与其他答案中使用的some()函数不同,这个函数不仅返回一个布尔值(true/false) 相反,它要么返回子字符串(如果它在数组中找到),要么返回undefined 更进一步,允许您选择是否需要部分子字符串匹配(示例如下)
享受吧!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
在这里,found将被设置为'abc'。这将适用于精确的字符串匹配。
如果你用:
const found = arrayOfStrings.find(v => str.includes(v));
同样,found在本例中被设置为'abc'。这不允许部分匹配,所以如果str被设置为'ab', found将是未定义的。
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
代替。如果str被设为'ab' found就会被设为'abc'
容易peasy !
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
我并不是建议你去扩展/修改String的原型,但这是我所做的:
String.prototype.includes ()
String.prototype.includes = function (includes) { console.warn("String.prototype.includes() has been modified."); return function (searchString, position) { if (searchString instanceof Array) { for (var i = 0; i < searchString.length; i++) { if (includes.call(this, searchString[i], position)) { return true; } } return false; } else { return includes.call(this, searchString, position); } } }(String.prototype.includes); console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 不区分大小写的列表排序,没有降低结果?
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- 如何在Java中将int[]转换为Integer[] ?
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组