Really Nice Code Really Nice Code - 1 year ago 112
Javascript Question

JavaScript: check if string contains '.' (a full-stop)

I am trying to search a string to see if it contains a period "."
I loaded the value of an input field into a variable then ran a javascript string search() method on that variable.

var _email = document.getElementById(Input).value;
var contains_dot =".");

The contains_dot variable should return -1 if a period is not found in the string OR a number representing the position of the match.

Sadly... the variable 'contains_dot' returns nothing but 0 every time.
Am i doing something wrong? there a better way?

Answer Source

Why does that happen?

The reason why"."); returns 0 every time is because takes a regular expression as its input.

. means match any character in regex. In other words, if your input has at least one character of anything, it will return 0.

The Solution

If you simply change it to\./);, it will work exactly as you intended.

Browser support: All known browsers

If you don't care about browser support, you may also use _email.includes('.'); as mentioned by Cade Brown.

See here for reference. Browser support: Only Chrome 41+ and Firefox 40+ (recent browsers)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download