I apologize if this seems like a dumb question, but how would I go about searching a string to see if it contains a period? I've tried searching:
var p="This is text without a period, What now?"
alert(p.search("."));
I was under the impression that it should return -1 because there is no period in that sentence. However, it always returns 0.
Am I missing something?
There's many ways to do this, I would probably use indexOf() just to see if a character exists in a string :
alert( p.indexOf(".") != -1 ); // true or false
According to MDN, search() "Executes the search for a match between a regular expression and this String object.", so that would be :
alert( p.search(/\./) );
which would give you -1, and the period has special meaning in a regex, and must be escaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With