jquery/javascript check string for multiple substrings - javascript

I need to check if a string has one of three substrings, and if yes, to implement a function. I know I can check for one substring using if (str.indexOf("term1") >= 0) but is there a way to check for multiple substrings short of using several instances of this code?
TIA

if (/term1|term2|term3/.test("your string")) {
//youre code
}

This achieves dynamically and elegantly what you are trying to do
const terms = ["term1", "term2", "term3"]
const str = "very large string to check for term1, tern2, etc ..."
// check if the string has some of the terms
const result1 = terms.some(term => str.includes(term))
// check if the string has all the terms
const result2 = terms.every(term => str.includes(term))
This also makes it easy to filter an array of strings for an array of substrings
const terms = ["term1", "term2", "term3"]
const strings = ["very large string text ....", "another large string text"]
// filter the strings of the array that contain some of the substrings we're looking for
const result1 = strings.filter(str => terms.some(term => str.includes(term)))
// filter the strings of the array that contain all the substrings we're looking for
const result2 = strings.filter(str => terms.every(term => str.includes(term)))

You could use a loop. Maybe even create a helper function like so:
function ContainsAny(str, items){
for(var i in items){
var item = items[i];
if (str.indexOf(item) > -1){
return true;
}
}
return false;
}
Which you can then call like so:
if(ContainsAny(str, ["term1", "term2", "term3"])){
//do something
}

Maybe this:
if (str.indexOf("term1") >= 0 || str.indexOf("term2") >= 0 || str.indexOf("term3") >= 0)
{
//your code
}

The .map() function can be used to convert an array of terms into an array of booleans indicating if each term is found. Then check if any of the booleans are true.
Given an array of terms:
const terms = ['term1', 'term2', 'term3'];
This line of code will return true if string contains any of the terms:
terms.map((term) => string.includes(term)).includes(true);
Three examples:
terms.map((term) => 'Got term2 here'.includes(term)).includes(true); //true
terms.map((term) => 'Not here'.includes(term)).includes(true); //false
terms.map((term) => 'Got term1 and term3'.includes(term)).includes(true); //true
Or, if you want to wrap the code up into a reusable hasTerm() function:
const hasTerm = (string, terms) =>
terms.map(term => string.includes(term)).includes(true);
hasTerm('Got term2 here', terms); //true
hasTerm('Not here', terms); //false
hasTerm('Got term1 and term3', terms); //true
Try it out:
https://codepen.io/anon/pen/MzKZZQ?editors=0012
.map() documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Note:
This answer optimizes for simplicity and readability. If extremely large arrays of terms are expected, use a loop that short-circuits once a term is found.

You can do something like
function isSubStringPresent(str){
for(var i = 1; i < arguments.length; i++){
if(str.indexOf(arguments[i]) > -1){
return true;
}
}
return false;
}
isSubStringPresent('mystring', 'term1', 'term2', ...)

If you want to check for multiple string matches and highlight them, this code snippet works.
function highlightMatch(text, matchString) {
let textArr = text.split(' ');
let returnArr = [];
for(let i=0; i<textArr.length; i++) {
let subStrMatch = textArr[i].toLowerCase().indexOf(matchString.toLowerCase());
if(subStrMatch !== -1) {
let subStr = textArr[i].split('');
let subStrReturn = [];
for(let j=0 ;j<subStr.length; j++) {
if(j === subStrMatch) {
subStrReturn.push('<strong>' + subStr[j]);
} else if (j === subStrMatch + (matchString.length-1)){
subStrReturn.push(subStr[j] + '<strong>');
} else {
subStrReturn.push(subStr[j]);
}
}
returnArr.push(subStrReturn.join(''));
} else {
returnArr.push(textArr[i]);
}
}
return returnArr;
}
highlightMatch('Multi Test returns multiple results', 'multi');
=> (5) ['<strong>Multi<strong>', 'Test', 'returns', '<strong>multi<strong>ple', 'results']

Related

(Javascript) How can I seperate a string based on an if statement that checks for a number?

So i'm trying to build a function that can simplify expressions but I can't seem to find a way to seperate the terms into 2 different arrays (numbers and letters). The result of the code below is "32xy" instead of just "32".
Also it would be great to know if there is a better way to check for a number or selection of characters in javascript.
var newArr;
var numArr = [];
var letArr = [];
function splitTerm (term) {
for (var i=0; i<term.length; i++){
newArr = term.split('');
}
for (var item of newArr){
if (item === '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9') {
numArr.push(item);
} else {
letArr.push(item);
}
}
$('#num').html(numArr.join(''));
}
splitTerm("32xy");
if (item === '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')
This should be
if (['0','1','2','3','4','5','6','7','8','9'].includes(item)) {
Also, you do'nt need to do that loop at the top of the function.
newArr = term.split(''); is fine to just run once.
Your code can be improved in many ways:
newArr, numArr, and letArr are only used inside the function, so you should declare them inside the function.
The for loop iterating from 0 to term.length does nothing except repeatedly assign the same thing to newArr, so it doesn't need to be there.
You can use a regex to test if something is a number.
function splitTerm(term) {
var newArr = term.split("");
for (var item of newArr) {
if (/\d/.test(item)) {
newArr.push(item);
} else {
letArr.push(item);
}
}
$("#num").html(numArr.join(""));
}
Another option - use regex
const splitTerm = (str) => {
// Use regexp to extract characters and digits
return {
dig: str.match(/\d+/g).join(''),
char: str.match(/[^\d]+/g).join(''),
};
};
// Run
const res = splitTerm("32xy");
// Log
console.log(res);
Here is the edited version
var newArr;
var numArr = [];
var letArr = [];
function splitTerm (term) {
numArr = Array.from(term).filter((elem) => /^[0-9]$/i.test(elem));
console.log(numArr.join(''));
}
splitTerm("322xy");
but you can actually use the value directly without function call;
$('#num').html(Array.from('32xy').filter((elem) => /^[0-9]$/i.test(elem)).join(''));
You can use .replace() with regular expression in your function.
console.log("32xy".replace(/[^0-9]/g, '')); // 32
console.log("aaa32xy".replace(/[^0-9]/g, '')); // 32
console.log("aaa3bb2xy".replace(/[^0-9]/g, '')); // 32

How to check if 2 strings separated by delimiters have matching word

Trying to check if 2 strings have matching word return true.
let 1st_string = chin, kore, span;
let 2nd_string = chin eng kore zulu
1st_string.split(',').indexOf(2nd_string) > -1
I tried above code but always returns false. I need to return true as 2_nd string contains 2 matching words from 1st_string.
Solved the names and values of the variables you can do the following
let first_string = 'chin, kore, span';
let second_string = 'chin eng kore zulu';
const array1 = first_string.split(',').map(string => string.trim());
const array2 = second_string.split(' ');
function exist(list1, list2) {
for (const element of list1) {
if (list2.includes(element)) {
return true;
}
}
return false;
}
const result = exist(array1, array2);
console.log(result);
1st_string is not a valid variable name
split the first string and use Array.some() to see if the second string has any of the words in the resulting array :
let string_1 = 'chin, kore, span';
let string_2 = 'chin eng kore zulu';
const check = (str1, str2) => {
return str1.split(',').some(word => str2.includes(word));
}
console.log(check(string_1, string_2))
I think your second string will also contain a comma in between the words if yes then it is easy to achieve.
you can split the string 1 and 2 with a comma as delimiter like this
let firstString = 1st_string.split(',');
let secondString = 2nd_string.split(',');
after doing you will get the firstString and secondString variable as array then you can iterate the first array and check for duplicate using includes methods
for (let i in firstString) {
if(secondString.includes(firstString[i])){
//you can do whatever you want after finding duplicate here;
}
}

Check if string contains set of other string

I want to check if string one in array contain the letters from words in string 2. Here's my example array:
(["Floor", "far"]);
function should return false because "a" is not in string "Floor"
But for array like this:
(["Newbie", "web"]);
It should return true because all of letters from "web" are in "Newbie".
Here's my code so far...
function mutation(arr) {
var newArr = [];
for (i=0; i<arr.length; i++) {
newArr.push(arr[i].toLowerCase().split(""));
}
for (i=0; i<newArr.length; i++) {
for (j=0; j<newArr[i].length; j++) {
console.log(newArr[0][j]+ (newArr[1][j]));
}
}
}
mutation(["Newbie", "web"]);
I know that it won't work and I'm out of ideas how to make it. I try to make a set of all letters in two array and compare them. If there is at least one false the function should return false. Should I nest indexOf() method somewhere?
I think this should work for you. Break up the string of letters to check for into an array. Iterate over the array getting each letter and checking if the string passed in contains the letter, setting our result to false if it doesn't.
function mutation(arr) {
var charArr = arr[1].toLowerCase().split("");
var result = true;
charArr.forEach(element => {
if (!arr[0].toLowerCase().includes(element)) {
result = false;
}
});
return result;
}
console.log(mutation(["Newbie", "web"]));
The cool way would be:
const mutation =([one, two]) => (set => [...two.toLowerCase()].every(char => set.has(char)))(new Set(one.toLowerCase()));
How it works:
At first we destructure the passed array into the first and the second word:
[one, two]
Now that we got both, we build up a Set of characters from the first word:
(set => /*...*/)(new Set(one))
All that in an IIFE cause we need the set here:
[...two].every(char => set.has(char))
That spreads the second word in an array, so we got an array of chars and then checks if all characters are part of the set we built up from the other word.
If you want to be sure that one word, which might have several repeating letters, is contained in another, use Array.reduce() to count the letters, and store create a map of letter -> counts. Do that for both words. Check if all entries of 2nd word are contained in the 1st word map using Array.every():
const countLetters = (w) =>
w.toLowerCase()
.split('')
.reduce((r, l) => r.set(l, (r.get(l) || 0) + 1), new Map());
const mutation = ([a, b]) => {
const al = countLetters(a);
const bl = countLetters(b);
return [...bl].every(([k, v]) => v <= (al.get(k) || 0));
};
console.log(mutation(["Floor", "far"])); // false
console.log(mutation(["Floor", "for"])); // true
console.log(mutation(["Floor", "foroo"])); // false
console.log(mutation(["Newbie", "web"])); // true

multiple conditions for JavaScript .includes() method

Just wondering, is there a way to add multiple conditions to a .includes method, for example:
var value = str.includes("hello", "hi", "howdy");
Imagine the comma states "or".
It's asking now if the string contains hello, hi or howdy. So only if one, and only one of the conditions is true.
Is there a method of doing that?
You can use the .some method referenced here.
The some() method tests whether at least one element in the array
passes the test implemented by the provided function.
// test cases
const str1 = 'hi hello, how do you do?';
const str2 = 'regular string';
const str3 = 'hello there';
// do the test strings contain these terms?
const conditions = ["hello", "hi", "howdy"];
// run the tests against every element in the array
const test1 = conditions.some(el => str1.includes(el));
const test2 = conditions.some(el => str2.includes(el));
// strictly check that contains 1 and only one match
const test3 = conditions.reduce((a,c) => a + str3.includes(c), 0) == 1;
// display results
console.log(`Loose matching, 2 matches "${str1}" => ${test1}`);
console.log(`Loose matching, 0 matches "${str2}" => ${test2}`);
console.log(`Exact matching, 1 matches "${str3}" => ${test3}`);
Also, as a user mentions below, it is also interesting to match "exactly one" appearance like mentioned above (and requested by OP). This can be done similarly counting the intersections with .reduce and checking later that they're equal to 1.
With includes(), no, but you can achieve the same thing with REGEX via test():
var value = /hello|hi|howdy/.test(str);
Or, if the words are coming from a dynamic source:
var words = ['hello', 'hi', 'howdy'];
var value = new RegExp(words.join('|')).test(str);
The REGEX approach is a better idea because it allows you to match the words as actual words, not substrings of other words. You just need the word boundary marker \b, so:
var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word
That should work even if one, and only one of the conditions is true :
var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];
function contains(target, pattern){
var value = 0;
pattern.forEach(function(word){
value = value + target.includes(word);
});
return (value === 1)
}
console.log(contains(str, arr));
You could also do something like this :
const str = "hi, there"
const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');
console.log(res);
Whenever one of your includes return true, value will be true, otherwise, it's going to be false. This works perfectly fine with ES6.
That can be done by using some/every methods of Array and RegEx.
To check whether ALL of words from list(array) are present in the string:
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
To check whether ANY of words from list(array) are present in the string:
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
Here's a controversial option:
String.prototype.includesOneOf = function(arrayOfStrings) {
if(!Array.isArray(arrayOfStrings)) {
throw new Error('includesOneOf only accepts an array')
}
return arrayOfStrings.some(str => this.includes(str))
}
Allowing you to do things like:
'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True
Not the best answer and not the cleanest, but I think it's more permissive.
Like if you want to use the same filters for all of your checks.
Actually .filter() works with an array and returns a filtered array (which I find easier to use too).
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
var conditions = ["hello", "hi", "howdy"];
// Solve the problem
var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
console.log(res1); // ["hi, how do you do?"]
console.log(res2); // []
// More useful in this case
var text = [str1, str2, "hello world"];
// Apply some filters on data
var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
// You may use again the same filters for a different check
var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));
console.log(res3); // []
console.log(res4); // ["hi, how do you do?", "hello world"]
Another one!
let result
const givenStr = 'A, X' //values separated by comma or space.
const allowed = ['A', 'B']
const given = givenStr.split(/[\s,]+/).filter(v => v)
console.log('given (array):', given)
// given contains none or only allowed values:
result = given.reduce((acc, val) => {
return acc && allowed.includes(val)
}, true)
console.log('given contains none or only allowed values:', result)
// given contains at least one allowed value:
result = given.reduce((acc, val) => {
return acc || allowed.includes(val)
}, false)
console.log('given contains at least one allowed value:', result)
Exact matching with array data/
const dataArray = ["amoos", "rifat", "hello"];
const findId = ( data, id ) => {
let res = data.find(el => el === id )
return res ? true : false;
}
console.log( findId( dataArray, 'Hi') ) // false
console.log( findId( dataArray, 'amoos') ) // true
const givenArray = ['Hi , how are you', 'how are you', 'howdy, how you doing']
const includeValues = ["hello", "hi", "howdy"]
const filteredStrArray = givenArray.filter(str => includeValues.some(value => str.toLowerCase().includes(value)))
console.log(filteredStrArray);
You can do this
["hello", "hi", "howdy"].includes(str)
Def an old thread but still getting newer replies.
I didn't see it on the results and it's one of the easiest ways to use .includes to search for multiple things in a string at once.
Depending on what you are trying to do with it just run a for loop that runs through an array of items you want to check a string for using .includes.
Const text = ' does this include item3? ';
For(i = 0; i < arr.length; i++)
{if (text.includes(arr[i])){/* do whatever */ } }
It will return true if any of those items are in that string and then you can have it do whatever.. execute a function, change a variable etc... You can also add what to do if it's false in the if statement as well.
It's worth noting though that it will execute that code for each item that is in the list that returns true so make sure you compensate for that in the code you want executed.
Edit- you could also convert this to a function set it up to pass arguments that are the multiple things you check to see if the string includes and just have it return true or false and you can do whatever with that information outside of the function.
it depends what context you're using it in.
I used it on an object to check if any of the keys had an empty string or null as its value and it worked
Object.values(object).includes('' || null)
string.match( /apple|banana/ ) // <-- Use Regex
maybe late but here is my solution for an array and two or more items
/one|two/.test(['one', 'two', 'three', 'four'].join(' '))
console.log(/one|two/.test(['one', 'two', 'three', 'four'].join(' ')))
--[wrong anwser, do not copy]--
Extending String native prototype:
if (!String.prototype.contains) {
Object.defineProperty(String.prototype, 'contains', {
value(patterns) {
if (!Array.isArray(patterns)) {
return false;
}
let value = 0;
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i];
value = value + this.includes(pattern);
}
return (value === 1);
}
});
}
Allowing you to do things like:
console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True
1 Line solution:
String/Array.prototype.includes('hello' || 'hi' || 'howdy');
let words = 'cucumber, mercy, introduction, shot, howdy'
words.includes('hi' || 'howdy' || 'hello') // true
words.includes('hi' || 'hello') // false
How about ['hello', 'hi', 'howdy'].includes(str)?

How to check if a string contains text from an array of substrings in JavaScript?

Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.
Two approaches for you:
Array some method
Regular expression
Array some
The array some method (added in ES5) makes this quite straightforward:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Even better with an arrow function and the newish includes method (both ES2015+):
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
Regular expression
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false if substring exists\does'nt exist
Needs ES6 support
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
}
}
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);
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
Here's what is (IMO) by far the best solution. It's a modern (ES6) solution that:
is efficient (one line!)
avoids for loops
unlike the some() function that's used in the other answers, this one doesn't just return a boolean (true/false)
instead, it either returns the substring (if it was found in the array), or returns undefined
goes a step further and allows you to choose whether or not you need partial substring matches (examples below)
Enjoy!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
Here, found would be set to 'abc' in this case. This will work for exact string matches.
If instead you use:
const found = arrayOfStrings.find(v => str.includes(v));
Once again, found would be set to 'abc' in this case. This doesn't allow for partial matches, so if str was set to 'ab', found would be undefined.
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
instead. So if str was set to 'ab', found would be set to 'abc'.
Easy peasy!
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
edit:
If the order of the tests doesn't matter, you could use this (with only one loop variable):
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)
For full support ;)
For full support (additionally to #ricca 's verions).
wordsArray = ['hello', 'to', 'nice', 'day']
yourString = 'Hello. Today is a nice day'.toLowerCase()
result = wordsArray.every(w => yourString.includes(w))
console.log('result:', result)
If the array is not large, you could just loop and check the string against each substring individually using indexOf(). Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
Example usage:
var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
This way you can take a predefined array and check if it contains a string:
var parameters = ['a','b']
parameters.includes('a') // true
Best answer is here:
This is case insensitive as well
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
const str = 'Does this string have one or more strings from the array below?';
const arr = ['one', 'two', 'three'];
const contains = arr.some(element => {
if (str.includes(element)) {
return true;
}
return false;
});
console.log(contains); // true
Not that I'm suggesting that you go and extend/modify String's prototype, but this is what I've done:
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
building on T.J Crowder's answer
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:
Array.prototype.check = function (s) {
return this.some((v) => {
return s.indexOf(v) >= 0;
});
};
Using underscore.js or lodash.js, you can do the following on an array of strings:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
If you're working with a long list of substrings consisting of full "words" separated by spaces or any other common character, you can be a little clever in your search.
First divide your string into groups of X, then X+1, then X+2, ..., up to Y. X and Y should be the number of words in your substring with the fewest and most words respectively. For example if X is 1 and Y is 4, "Alpha Beta Gamma Delta" becomes:
"Alpha" "Beta" "Gamma" "Delta"
"Alpha Beta" "Beta Gamma" "Gamma Delta"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
If X would be 2 and Y be 3, then you'd omit the first and last row.
Now you can search on this list quickly if you insert it into a Set (or a Map), much faster than by string comparison.
The downside is that you can't search for substrings like "ta Gamm". Of course you could allow for that by splitting by character instead of by word, but then you'd often need to build a massive Set and the time/memory spent doing so outweighs the benefits.
convert_to_array = function (sentence) {
return sentence.trim().split(" ");
};
let ages = convert_to_array ("I'm a programmer in javascript writing script");
function confirmEnding(string) {
let target = "ipt";
return (string.substr(-target.length) === target) ? true : false;
}
function mySearchResult() {
return ages.filter(confirmEnding);
}
mySearchResult();
you could check like this and return an array of the matched words using filter
I had a problem like this. I had a URL, I wanted to check if the link ends in an image format or other file format, having an array of images format. Here is what I did:
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
// false
You can check like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var list = ["bad", "words", "include"]
var sentence = $("#comments_text").val()
$.each(list, function( index, value ) {
if (sentence.indexOf(value) > -1) {
console.log(value)
}
});
});
</script>
</head>
<body>
<input id="comments_text" value="This is a bad, with include test">
</body>
</html>
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
Use filter :
obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
var str = "A for apple"
var subString = ["apple"]
console.log(str.includes(subString))

Categories