Check if a String contains a Period using JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Kylo

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee