Any string in Javascript has a match()
function that accepts a regex and returns null
if it doesn't match.
For instance, if you have:
var s = "Hello I'm 301";
you can test it with:
if (s.match(/^[a-z0-9 ]*$/i)
alert("string is ok!");
else
alert("string is bad!");
On to the regex: /^[a-z0-9 ]*$/i
The caret(^
) at the beginning and the dollar ($
) at the end are anchors. They mean "beginning of string" and "end of string".
They force the regex to cover the entire string, not just portions. The square brackets define a character range: letters and numbers, and also space.
Without the caret and the dollar (the anchors), your regex would have matched any valid character and would have returned true.
The final "i"
is a regexp option, meaning "case insensitive".
Hope that helps!