如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:17:18  来源:igfitidea点击:

How can I check if my string contains a period in JavaScript?

javascriptregexstring

提问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 indexOfmethod: someString.indexOf('.') != -1. No need for a regex.

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

回答by Olivier Krull

I know this is an old question, but here is a new way to do it (not supported in older browsers -> can I use):

我知道这是一个老问题,但这里有一种新方法(旧浏览器不支持 ->我可以使用):

str.includes('.'); //returns true or false

docs

文档

回答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 Stringinstances with a containsmethod 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!";}