Reputation: 3417
I'm using google scripts and as a result, I can't use ES6 or ES5 in my HTML code. I'd like to check if a string variable might include one or multiple of the words below. The example below doesn't work. How is this suppose to write this?
string.indexOf("Word1" || "Word2" || "Word3") > -1
Upvotes: 2
Views: 2498
Reputation: 2557
// Polyfill
String.prototype.includes = String.prototype.includes || function(s) {
return this.indexOf(s) >= 0
}
// ES6:
// const strIncludes = (string, words) =>
// words.some(w => string.includes(w))
function strIncludes(string, words) {
return words.some(function(s) {
return string.includes(s)
})
}
console.log(strIncludes('hello world and goodbye', ['hi', 'hello']))
Upvotes: 0
Reputation: 370679
One option is to use a regular expression instead:
/Word1|Word2|Word3/.test(string)
Or iterate over an array of words to search for:
var found = false;
var arr = ['Word1', 'Word2', 'Word3']
for (var i = 0; i < arr.length; i++) {
if (string.indexOf(arr[i]) !== -1) {
found = true;
break;
}
}
// use `found` variable
If you want to ensure that the string doesn't contain any of those words with a regex, then continually match characters from the beginning of the string to the end while using negative lookahead for the alternated pattern:
^(?:(?!Word1|Word2|Word3)[\s\S])+$
https://regex101.com/r/FsChvB/1
But that's strange, it'd be a lot easier just to use the same test as above, and invert it.
var stringContainsForbiddenWords = !/Word1|Word2|Word3/.test(string)
Upvotes: 4
Reputation: 114
Just make it a for loop to check each array element.
var array = ["test234", "test9495", "test234", "test93992", "test234"];
for (i=0;i<array.length;i++) {
if (array[i] == "test234") {
document.write(i + "<br>");
}
}
Upvotes: 0