if 语句和文本输入值

if statements and textinput value

如果我有一个文本字段,并且我想使用 IF 语句来检查该文本字段,例如,我可以这样做

if (thistxt.text=="query")
{  
thisbool = "true";
}

现在假设我想使用 IF 语句调用同一个文本字段,但我不想提取整个短语,(查询)可能只是它的开头或结尾,我该怎么做像那样?假设我想在该文本字段包含 "ery" 或以 "ery" 结尾但不一定完全等于 "ery" 时激活 IF 语句。

TextField.text returns a String. Strings have the indexOf() method 其中 returns 如果找到子串的位置,否则返回 -1。这意味着你可以这样做:

if (thistxt.text.indexOf('ery') >= 0) {
    thisbool = true;
}

还有更高级的match() method that uses either strings or regular expressions:

if (thistxt.text.match('ery').length > 0) {
    thisbool = true;
}

要匹配输入开头或结尾的字符串,您必须使用正则表达式。幸运的是,与正则表达式的完整功能相比,这些类型匹配的模式是微不足道的——类似于:

if (thistxt.text.match(/^ery/).length > 0) // Match at the start.
if (thistxt.text.match(/ery$/).length > 0) // Match at the end.