类似于SQL的JavaScript运算符"喜欢"

ind*_*ndu 57 javascript

可能重复:
在JavaScript中模拟SQL LIKE

JavaScript中的like运算符是否与SQL中的运算符类似?感谢解释和示例.

cle*_*tus 74

您可以在Javascript中使用正则表达式来进行字符串的模式匹配.

例如:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

match()测试是很像WHERE s LIKE 'hello%'的SQL.

  • 最好在这里使用`test`(顺便说一下,它应该更快),因为不需要实际的匹配结果. (13认同)
  • 最肯定的是,在这里使用 `/regex/.test(s)` ,除非您想对匹配项执行某些操作 - /sf/answers/765809691/ (3认同)

Noo*_*ilk 27

没有.

您想使用:.indexOf("foo")然后检查索引.如果它> = 0,则它包含该字符串.

  • 如果情况不同,则不起作用.你需要使用:`myString.toLowerCase().indexOf("foo")` (2认同)

Ash*_*Ash 19

使用字符串对象匹配方法:

// Match a string that ends with abc, similar to LIKE '%abc'
if (theString.match(/^.*abc$/)) 
{ 
    /*Match found */
}

// Match a string that starts with abc, similar to LIKE 'abc%'
if (theString.match(/^abc.*$/)) 
{ 
    /*Match found */
}
Run Code Online (Sandbox Code Playgroud)


Hav*_*ard 8

您可以检查String.match()String.indexOf()方法.