Sheehan Alam
Sheehan Alam

Reputation: 60909

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

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;

Upvotes: 18

Views: 55656

Answers (6)

Getter Jetter
Getter Jetter

Reputation: 2081

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

Upvotes: 5

SeanCannon
SeanCannon

Reputation: 78006

Use 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")
}

Upvotes: 44

Dan Tao
Dan Tao

Reputation: 128377

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.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.

Upvotes: 1

ratsbane
ratsbane

Reputation: 890

Use indexOf. It returns an integer showing the position of a substring, or -1 if it isn't found.

For example:

var test="myfile.doc"
if (test.indexOf('.')) {alert("Period found!";}
else {alert("Period not found.  Sorry!";}

Upvotes: 0

jwodder
jwodder

Reputation: 57600

Just test the return value of the indexOf method: someString.indexOf('.') != -1. No need for a regex.

Upvotes: 7

james
james

Reputation: 3583

Some simple regex will do.

 if (myString.match(\.)) {
   doSomething();
 }

Upvotes: 2

Related Questions