如何在 JavaScript 中检查我的字符串是否包含句点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6560307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if my string contains a period in JavaScript?
提问by Sheehan Alam
I want to be able to detect if a string has a . in it and return true/false based on that.
我希望能够检测字符串是否具有 . 在其中并基于此返回真/假。
For example:
例如:
"myfile.doc" = TRUE
vs.
对比
"mydirectory" = FALSE;
回答by AlienWebguy
Use indexOf()
用 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")
}
回答by jwodder
Just test the return value of the indexOf
method: someString.indexOf('.') != -1
. No need for a regex.
只需测试方法的返回值indexOf
:someString.indexOf('.') != -1
。不需要正则表达式。
回答by Olivier Krull
回答by Dan Tao
Just to add to what's already been said:
只是为了补充已经说过的内容:
There are differing opinions on whether or not this is a good idea, but you can extend all String
instances with a contains
method if you like:
关于这是否是一个好主意有不同的意见,但如果您愿意,可以String
使用一种contains
方法扩展所有实例:
String.prototype.contains = function(char) {
return this.indexOf(char) !== -1;
};
I tend to like this sort of thing, when it's (relatively) unambiguous what a method will do.
我倾向于喜欢这种事情,当它(相对)明确一个方法将做什么时。
回答by james
Some simple regex will do.
一些简单的正则表达式就可以了。
if (myString.match(\.)) {
doSomething();
}
回答by ratsbane
Use indexOf. It returns an integer showing the position of a substring, or -1 if it isn't found.
使用 indexOf。它返回一个整数,显示子字符串的位置,如果未找到,则返回 -1。
For example:
例如:
var test="myfile.doc"
if (test.indexOf('.')) {alert("Period found!";}
else {alert("Period not found. Sorry!";}