使用javascript从字符串中确定操作符
Determining the operator from a string using javascript
我需要你的帮助
我需要编写一个javascript函数来检查输入到文本框中的字符串从而确定SQL操作符
的例子:
var field1 = document.getElementById('field1').value
var field2 = document.getElementById('field2').value
var field3 = document.getElementById('field3').value
function validate(textbox) {
var operator
if ('%' is the first character placed before and after the value) { then operator = LIKE }
else if ('%' is the first character placed before the value) { then operator = LIKE }
else if ('%' is the last character placed after the value) { then operator = LIKE }
else { operator equals "=" } //default
alert(operator)
}
功能示例:
validate(field1)
尝试如下:
function validate(value) {
var operator = '=';
// Check for '%' at the beginning or ending of the value.
if (value.length > 0 && (value[0] == '%' || value[value.length - 1] == '%')) {
operator = 'LIKE';
}
alert(operator);
}
也就是说,根据您的目标用户,如果您包含一组单选按钮选项,如"匹配开始","匹配结束"answers"匹配任何地方",而不是要求他们理解SQL字符串匹配语法,对他们来说可能更容易。
例如:<input id="matchBeginning" type="radio" name="matchMode" value="beginning" />
<label for="matchBeginning">Match beginning of text</label>
<input id="matchEnding" type="radio" name="matchMode" value="ending" />
<label for="matchEnding">Match ending of text</label>
<input id="matchAnywhere" type="radio" name="matchMode" value="anywhere" />
<label for="matchAnywhere">Match anywhere in text</label>
<input id="matchExact" type="radio" name="matchMode" value="exact" />
<label for="matchExact">Match entire text</label>
<input id="field1" type="text" />
然后可以传递matchMode
的值(即。"开始","结束","任何地方"或"确切")以及搜索词到您的服务器,它将按照matchMode
的规定向搜索词添加"%"字符。
您可以使用正则表达式。看起来,如果字符串包含%
,则操作符是LIKE
。所以你可以这样写:
var operator = "=";
//If the string starts with a % or ends with a %
//the operator is "LIKE"
if(/^%/.test(str) || /%$/.test(str)) {
operator = "LIKE";
}
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- jQuery中是否内置了任何字符串格式化函数
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- ng打开空字符串
- 正则表达式在字符串中找到base64
- 如何将字符串值从php页面发送到java脚本页面
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- 字符串在将其传递给另一个活动Android JavaScript时读取Null
- 对id以某个字符串开头的元素进行计数
- Javascript逻辑运算符和字符串/数字
- 反向字符串比较
- 如何有效地将游戏数据存储在URL查询字符串中
- Typeof操作符返回一个非空的字符串
- Javascript数字比较操作符是如何处理字符串的
- 使用javascript从字符串中确定操作符
- 如何从字符串调用和执行操作符
- 操作符<或比;比较两个字符串时工作
- 如何将检查字符串是否存在与?操作符
- 在字符串的变量中添加操作符
- & # 39;上# 39;JavaScript中的操作符.字符串比较