使用javascript从字符串中确定操作符

Determining the operator from a string using javascript

本文关键字:操作符 字符串 javascript 使用      更新时间:2023-09-26

我需要你的帮助

我需要编写一个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";
}