nic*_*ber 8 javascript string if-statement indexof contain
我目前正在试图找出如何解决上述问题.具体来说,我想检查的字符串中不同时含有大写和小写字母的单词"流".
到目前为止,这是我的代码:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
Run Code Online (Sandbox Code Playgroud)
代码显然不起作用,因为结果不是我期望的结果.indexOf在使用以下语法变体之前,我还尝试使用该方法:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
Run Code Online (Sandbox Code Playgroud)
这些变化似乎都不适合我.有人可以给我一个暗示这里有什么问题吗?我indexOf之前多次使用过该方法,但总是在我想检查字符串是否包含特定单词时,而不是相反.
我建议使用String+toLowerCase和检查String#indexOf,因为它适用于每个浏览器.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
Run Code Online (Sandbox Code Playgroud)
indexOf().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)));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18007 次 |
| 最近记录: |