Check if a String contains a Period using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 27, 2021

banner

Check out my new book

Check if a String contains a Period #

Use the includes() method to check if a string contains a period, e.g. str.includes('.'). The includes method will return true if the string contains a period, otherwise false will be returned.

index.js
const str = 'hello.world'; if (str.includes('.')) { console.log('✅ String contains a period'); } else { console.log('⛔️ String does not contain a period'); }

We used the String.includes method to check if a string contains a period.

The only parameter we passed to the method is the substring we want to search for in the string.

If the substring is found in the string, the method returns true, otherwise false is returned.

The includes method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.

To check if a string contains a period, call the indexOf method on the string, passing it a period as a parameter, e.g. str.indexOf('.'). The indexOf method will return -1 if the string doesn't contain a period, otherwise the index of the first period in the string will be returned.

index.js
const str = 'hello.world'; if (str.indexOf('.') !== -1) { console.log('✅ String contains a period'); } else { console.log('⛔️ String does not contain a period'); }

The String.indexOf method returns the index of the first occurrence of a value in a string.

If the value is not contained in the string, -1 is returned.

In our if statement, we check if the return value from the method is not equal to -1. If it isn't, we can conclude the string contains a period.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.