I think I won’t be far from truth by saying that you can see regular expressions as a language which you can use to search, replace and extract data from/in an existing string. Unfortunately, regular expressions tend to be rather cryptic… and that means that they might be hard to read and/or write. A regular expression is always a string which might use one or more characters from a special characters’ list. Special characters are so called because they have a special meaning. For instance, \d means something like “match any digit”…I’m not going to show you all speciall characters here. Instead, I’ll redirect you to this page.
I’ve already mentioned that writing and reading complex regular expressions is not for those who have heart problems…the main problem I see with them is that, unlike traditional code, you can’t really use white spaces nor can you use comments for explaining something better (notice that I’m talking about the regular expression itself here). A regular expression string is really a compact string which gets harder and harder to read as you get better at understanding them…
var reg = new RegExp("\\d");
alert(reg.test("have 1 digit"));
The previous snippet introduced one of the methods exposed by the RegExp class: the test method. You can use it for checking if the string that was passed to it matches the regular expression encapsulated by that RegExp object. There’s still one more interesting thing to notice about the previous snippet: we had to escape the \ char since we’re using a string to define the regular expression.
alert(/\d/.test("have 1 digit"));
In case you’re wondering, the flag parameter can also be specified when using regular expression literals:
alert(/\d/g.test("have 1 digit"));
If you need to, you can pass several flags by just putting the corresponding letters after the ending slash (don’t worry to much about these flags…we’ll come back to them in future pots). Most of the time, you’ll probably end up using regular expressions literals due to their compactness (when compared with the equivalent RegExp instantiation).