admin管理员组

文章数量:1350044

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?

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?

Share Improve this question edited May 2, 2013 at 15:00 Naftali 146k41 gold badges247 silver badges304 bronze badges asked May 2, 2013 at 14:58 user1470118user1470118 4122 gold badges9 silver badges25 bronze badges 2
  • 2 FYI, the search method is a regular expression search, not a character match. In a regex, . matches any character, including that first "T". – Paul Roub Commented May 2, 2013 at 15:02
  • Ahhhh, that explains it! Thanks for that. – user1470118 Commented May 2, 2013 at 15:03
Add a ment  | 

3 Answers 3

Reset to default 11

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 want to stick to regex, you will need to escape the ., as it is a special regex character. To escape the dot in JavaScript Regex, you need to "cast" it to a character class. This is done via [].

alert(p.search("[.]"));

Working fiddle

use indexOf() method of a string for this

https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf

本文标签: javascriptDetecting if period exists in a stringStack Overflow