I found this reference very helpful because I tend to forget the difference between match, test, search and so on.
| Description | Example |
|---|---|
RegExp.exec(string) |
|
| Applies the RegExp to the given string, and returns the match information. | var match = /s(amp)le/i.exec("Sample text")
|
RegExp.test(string) |
|
| Tests if the given string matches the Regexp, and returns true if matching, false if not. | var match = /sample/.test("Sample text")
|
String.match(pattern) |
|
Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null. |
var str = "Watch out for the rock!".match(/r?or?/g)
|
String.search(pattern) |
|
| Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. | var ndx = "Watch out for the rock!".search(/for/)
|
String.replace(pattern,string) |
|
| Replaces matches with the given string, and returns the edited string. | var str = "Liorean said: My name is Liorean!".replace(/Liorean/g,'Big Fat Dork')
|
String.split(pattern) |
|
| Cuts a string into an array, making cuts at matches. | var str = "I am confused".split(/\s/g)
|
source: http://www.javascriptkit.com/javatutors/redev3.shtml