How to find if an array contains a specific string in JavaScript/jQuery?
You really don't need jQuery for this.
var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never
occurs
or
function arrayContains(needle, arrhaystack)
{
return (arrhaystack.indexOf(needle) > -1);
}
It's worth noting that array.indexOf(..)
is not supported in IE < 9, but jQuery's indexOf(...)
function will work even for those older versions.
Jquery check if array contains substring
You can use regexp to find the right price:
var regions = ["city1", "city2", "city3"];var address = "example address 42-200 City1 Poland";var address2 = "city3";var address3 = "city6";
function priceForAddress(address, regions) { var city = regions.find(function (region) { var reg = new RegExp(region, 'i'); return address.match(reg) !== null; }); if (city) { return '20$'; } else { return '4$/km'; }}
console.log(priceForAddress(address, regions));console.log(priceForAddress(address2, regions));console.log(priceForAddress(address3, regions));
How can one check if an array contains a substring?
The Array.prototype
has very useful .filter
function for your purpose.
const arr = ['positive', 'positron', 'negative', 'negatron'];
function findMatches() { let searchVal = document.getElementById('test').value; let res = arr.filter(el => el.indexOf(searchVal) > -1); document.getElementById('result').innerHTML = res.join(', ');}
<input type="text" id="test" /><button type="button" onclick="findMatches()">Find</button><br /> Array: ['positive', 'positron', 'negative', 'negatron']<br /><span id="result"></span>
How to check array if it contains a string with same text?
You can use array#filter
with string#includes
to check for substring in your array of string.
var cards = ["ace_of_clubs.png","2_of_clubs.png","3_of_clubs.png","ace_of_hearts.png"], f_string = cards.filter(card => card.includes("clubs"));console.log(f_string);
Check if an array of strings contains a substring
Because includes will compare '#' with each array element.
Let's try with some or find if you want to find if you want to get exactly element
var array = ["123", "456", "#123"];
var el = array.find(a =>a.includes("#"));
console.log(el)
How to find part of a string in array jQuery
Seeing that OP changed his original question: http://jsfiddle.net/c4qPX/2/ is a solution for both of them (there's no really difference for the algorithm if we're searching through the array of searched keys or searched values) - the point is what to compare.
var array1 = ['BA11', 'BA14', 'BA15'];
var array2 = ['GL156', 'GL24', 'GL31'];
var search = 'GL156DC';
$.each([array1, array2], function(index, value){
$.each(value, function(key, cell){
if (search.indexOf(cell) !== -1)
console.log('found in array '+index, cell);
});
});
How to check if a string contains text from an array of substrings in JavaScript?
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}"`);
}
Unable to determine if a string contains a word from an array
Change inArray
function with array.some(text => itag.textContent.includes(text))
.
Declare all variables via var or const or let
.
Instead of innerHTML
use textContent
. This will not try to parse the content
and will work faster.
var array = ["Hello", "Goodbye"];
var a = document.getElementsByClassName("here");
for (var i = 0; i < a.length; i++) { var itag = a[i].getElementsByTagName("i")[0]; var textContent = itag.textContent; if(array.some(text => textContent.includes(text))) { console.log(textContent); }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="here"><i><a href="link.php">Hello</a> | <a href="link2.php">Example</a></i></div>
<div class="here"><i><a href="link.php">Hey</a> | <a href="link2.php">Hello</a></i></div>
How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes
, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
Related Topics
Modifying Location.Hash Without Page Scrolling
Execute JavaScript Using Selenium Webdriver in C#
Can JavaScript Access a Filesystem
Chrome 65 Blocks Cross-Origin <A Download>. Client-Side Workaround to Force Download
Move the Mouse Pointer to a Specific Position
$ Variable (Dollar Sign) in Chrome
Difference Between Defer().Promise and Promise
Es6/Es2015 Object Destructuring and Changing Target Variable
Cannot Use Attr with an Object in D3 V4
JavaScript Promises - Reject VS. Throw
How to Reset (Clear) Form Through JavaScript
JavaScript Variable Definition: Commas VS. Semicolons
Need to Find Height of Hidden Div on Page (Set to Display:None)
How to Add "Href" Attribute to a Link Dynamically Using JavaScript
Scrape HTML Generated by JavaScript with Python
Is There a Max Number of Arguments JavaScript Functions Can Accept