Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 571
Sheehan Alam Avatar asked Jul 03 '11 00:07

Sheehan Alam


People also ask

How do you check if a string contains a set of characters in JavaScript?

You can check if a JavaScript string contains a character or phrase using the includes() method, indexOf(), or a regular expression. includes() is the most common method for checking if a string contains a letter or series of letters, and was designed specifically for that purpose.

How do you check if a string contains a text in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

Can a string have a period?

Abstract. In this paper we explore the notion of periods of a string. A period can be thought of as a shift that causes the string to match over itself. We obtain two sets of necessary and sufficient conditions for a set of integers to be the set of periods of some string (what we call the correlation of the string).

How do you check if a string contains a date in JavaScript?

Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.


1 Answers

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")
}
like image 180
AlienWebguy Avatar answered Sep 29 '22 01:09

AlienWebguy