2

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

3 Answers 3

4

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. How would that look if you wanted it 'not' to include the words using regular expressions?
0

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>"); } } 

Comments

0

// 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']))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.