非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。
当前回答
单线解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
如果子字符串存在\不存在,则返回true\false
需要ES6支持
其他回答
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
使用滤镜:
obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
我并不是建议你去扩展/修改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
var str = "A for apple" var subString = ["apple"] console.log (str.includes (subString))
全面支持(除了@ricca的版本)。
wordsArray = ['hello', 'to', 'nice', 'day'] yourString = '你好。今天天气不错’。 result = wordsArray。每个(w => yourstring .include (w)) console.log(“结果:”,结果)
基于t。j。克劳德的答案
使用转义的RegExp测试至少一个子字符串的“至少一次”出现。
函数buildSearch(substrings) { 返回新的RegExp( 子字符串 . map(函数(s) {s.replace返回 (/[.*+?^${}()|[\]\\]/ g , '\\$&');}) .join('{1,}|') + '{1,}' ); } var pattern = buildSearch(['hello','world']); console.log(模式。测试('你好')); console.log(模式。Test ('what a wonderful world')); console.log(模式。Test ('my name is…'));
推荐文章
- 窗口。亲近与自我。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:从对象属性数组中获取值数组