如何检查我的字符串是否包含JavaScript中的句点?

She*_*lam 10 javascript regex string

我希望能够检测字符串是否有.在其中并基于此返回true/false.

例如:

"myfile.doc" = TRUE
Run Code Online (Sandbox Code Playgroud)

"mydirectory" = FALSE;
Run Code Online (Sandbox Code Playgroud)

Ali*_*guy 31

使用 indexOf()

var str="myfile.doc";
var str2="mydirectory";

if(str.indexOf('.') !== -1)
{
  // would be true. Period found in file name
  console.log("Found . in str")
}

if(str2.indexOf('.') !== -1)
{
  // would be false. No period found in directory name. This won't run.
  console.log("Found . in str2")
}
Run Code Online (Sandbox Code Playgroud)

  • `indexOf` 在没有找到字符时返回 -1,而不是 0。 (3认同)

jwo*_*der 7

只需测试方法的返回值indexOf:someString.indexOf('.') != -1.不需要正则表达式.