How to check if my string contains a period in JavaScript?

I want to determine if there is a string. in it and return true / false based on this.

For instance:

"myfile.doc" = TRUE

against.

"mydirectory" = FALSE;
+8
source share
6 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")
}
Run code
+24
source

Just check the return value of the method indexOf: someString.indexOf('.') != -1. No need for regular expression.

+7
source

- .

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

:

, , String contains, :

String.prototype.contains = function(char) {
    return this.indexOf(char) !== -1;
};

, () .

+1

, , ( ):

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

docs

+1
source

Use indexOf. It returns an integer indicating the position of the substring, or -1 if it is not found.

For instance:

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

All Articles