I am currently trying to figure out how to solve the above named problem. Specifically I want to check if the string does not contain the word "stream" both in capital and lowercase letters.
Here's my code so far:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
The code does obviously not work as the results are not what I expect them to be.
I also tried to use the indexOf
method before using the following syntax variations:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf
method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
Use the Contains() method to check if a string contains a word or not.
To check if a string doesn't include a substring, call to the indexOf() method on the string, passing it the substring as a parameter. If the indexOf method returns -1 , then the substring is not contained in the string. Copied!
The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.
I suggest to use String+toLowerCase
and check with String#indexOf
, because it works in every browser.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
indexOf()
is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase()
or .toUpperCase()
:
const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
function testString(testData, lookup){
return testData.toLowerCase().indexOf(lookup) === -1;
}
function prettyPrint(yesNo){
return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}
console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With