我想要能够检测一个字符串中是否包含".",并根据结果返回 true/false。
例如:
例如:
"myfile.doc" = TRUE
对比。
"mydirectory" = FALSE;
"myfile.doc" = TRUE
对比。
"mydirectory" = FALSE;
使用 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")
}
只需测试indexOf
方法的返回值:someString.indexOf('.') != -1
。无需使用正则表达式。
仅补充已经说过的内容:
关于这是否是一个好主意,有不同的意见,但如果你愿意,你可以扩展所有的String
实例,加入一个contains
方法:
String.prototype.contains = function(char) {
return this.indexOf(char) !== -1;
};
我倾向于喜欢这种类型的事情,当一个方法的作用相对明确时。
一些简单的正则表达式就可以了。
if (myString.match(\.)) {
doSomething();
}
var test="myfile.doc"
if (test.indexOf('.')) {alert("Period found!";}
else {alert("Period not found. Sorry!";}
if (test.indexOf('.'))
这行代码的作用是检测indexOf
返回值是否为0,而不是应该测试的-1。因此,你的代码会将没有句点的字符串视为有句点,将以句点开头的字符串视为没有句点。请注意修正此错误。 - jwodder
indexOf
返回 -1,而不是 0。 - jwodder