Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  0] [ 4]  / answers: 1 / hits: 19393  / 8 Years ago, mon, october 3, 2016, 12:00:00

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 = _email.search(.);


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? ..is there a better way?



Please note:



contains_dot = _email.indexOf(.);


Does NOT work for this question as it returns 0 no matter what the input.


More From » string

 Answers
15

Why does that happen?



The reason why _email.search(.); returns 0 every time is because String.prototype.search 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 _email.search(/./);, 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)


[#60527] Thursday, September 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
noe

Total Points: 149
Total Questions: 91
Total Answers: 91

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;