Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if period exists in a string

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?

like image 270
user1470118 Avatar asked Nov 21 '25 17:11

user1470118


1 Answers

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.

like image 82
adeneo Avatar answered Nov 23 '25 05:11

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!