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 a string contains any element of an array in JavaScript
Problem lies in the for loop, which only iterates once since return ends the function, cutting off the for loop in the process. So, you can update the code like so to make the function only return once the for loop has been completed .
var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
function checker(value) { var prohibited = ['banana', 'apple'];
for (var i = 0; i < prohibited.length; i++) { if (value.indexOf(prohibited[i]) > -1) { return false; } } return true;}
arr = arr.filter(checker);console.log(arr);
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)
Check if a string contains any element of array
Using some()
const subject = "This process is flawless"
const matchArray = ["process", "procedure", "job"]
console.log(matchArray.some(i => subject.includes(i)))
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 if a string contains all the elements of an array in Javascript
Use every() function on the arr and includes() on the str;
Every will return true if the passed function is true for all it's items.
var str = 'apple_mango_banana';var arr = ['apple','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
In javascript, how do you search an array for a substring match
In your specific case, you can do it just with a boring old counter:
var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
value = windowArray[index];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
// Use `result` here, it will be `undefined` if not found
But if your array is sparse, you can do it more efficiently with a properly-designed for..in
loop:
var key, value, result;
for (key in windowArray) {
if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = windowArray[key];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
}
// Use `result` here, it will be `undefined` if not found
Beware naive for..in
loops that don't have the hasOwnProperty
and !isNaN(parseInt(key, 10))
checks; here's why.
Off-topic:
Another way to write
var windowArray = new Array ("item","thing","id-3-text","class");
is
var windowArray = ["item","thing","id-3-text","class"];
...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.
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");
})
Related Topics
How to Send a Variable Number of Arguments to a JavaScript Function
How to Capture an Arbitrary Number of Groups in JavaScript Regexp
Check If a JavaScript String Is a Url
Regular Expression to Get a String Between Parentheses in JavaScript
JavaScript - Get Array of Dates Between 2 Dates
How to Get Character Array from a String
Node.Js Plans to Support Import/Export Es6 (Ecmascript 2015) Modules
JavaScript % (Modulo) Gives a Negative Result for Negative Numbers
Jquery How to Bind Onclick Event to Dynamically Added HTML Element
Get the Element with the Highest Occurrence in an Array
How to Perform a Dns Lookup (Hostname to Ip Address) Using Client-Side JavaScript
When to Use Vanilla JavaScript VS. Jquery
How to Replace Innerhtml of a Div Using Jquery
How to Open a Bootstrap Modal Window Using Jquery