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)
Test if a string contains any of the strings from an array
EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.
public static boolean stringContainsItemFromList(String inputStr, String[] items) {
return Arrays.stream(items).anyMatch(inputStr::contains);
}
Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains)
.
You can also use .filter(inputStr::contains).findAny()
if you wish to return the matching string.
Important: the above code can be done using parallelStream()
but most of the time this will actually hinder performance. See this question for more details on parallel streaming.
Original slightly dated answer:
Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase()
or toUpperCase()
on both the input and test strings.
If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches()
helper method.
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
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}"`);
}
Check if string contains a value in array
Try this.
$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
Use stristr() or stripos() if you want to check case-insensitive.
Detect if string contains any element of a string array
In additional to answer of @Sh_Khan, if you want match some word from group:
let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
let worlds = wordGroups.flatMap { $0.components(separatedBy: " ")}
let match = worlds.filter { str.range(of:$0) != nil }.count != 0
javascript check if string contains words in array and replace them
In the body of the if
the variable string
is not available anymore because it's only valid in the callback of some
. So just loop over the blocked
words and do the replacement.
blocked.forEach(string => {
if (message.includes(string)) message = message.replace(string, "blocked");
})
In principle the check isn't necessary. If the search value is not contained in the string, nothing will be replaced, so you can just do the following:
blocked.forEach(string => {
message = message.replace(string, "blocked");
})
But be aware that String::replace(search, replacement)
only replaces the first occurence of search
if it is a string. So if your "badword" occurs more than once, only the first occurence will be replaced. So it might be better to define your blocked words as regex, because this way you can replace multiple occurrences.
var replacements = [
/badwordone/gi,
/badwordtwo/gi
]
replacements.forEach(r => {
message = message.replace(r, "blocked");
})
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>
Related Topics
PHP Pdo Insert Batch Multiple Rows with Placeholders
Syntax Error, Unexpected T_Encapsed_And_Whitespace, Expecting T_String or T_Variable or T_Num_String
Add ".Active" Class to the Current Page's Link in a Menu Using Jquery or PHP
Ajaxify Header Cart Items Count in Woocommerce
How to Use Curl and PHP Simple HTML Dom Parser with Object
PHP Get Content of Http 400 Response
Laravel Quick Start Guide Route Not Working
PHP - Get Last Week Number in Year
Php: How to Capture Browser Window Screen with PHP
How to Convert All Characters to Their HTML Entity Equivalent Using PHP
When and Why Should $_Request Be Used Instead of $_Get/$_Post/$_Cookie
Is There an Equivalent in C++ of PHP's Explode() Function
Turn Plain Text Urls into Active Links Using PHP
Set Product Sale Price Programmatically in Woocommerce 3
JSON_Decode() Returns Null Issues