Regular Expressions
From Ajax Patterns
This page overviews regular expressions (regexp/regex) in Javascript.
Contents |
|
[edit]
References
- The examples below are taken from the Javascrit Kit Tutorial
[edit]
Idioms
[edit]
Get an array of all matches
var string1="Peter has 8 dollars and Jane has 15" parsestring1=string1.match(/\d+/g) //returns the array [8,15]
[edit]
Run a string substitution/replacement
var string2="(304)434-5454"
parsestring2=string2.replace(/[\(\)-]/g, "") //Returns "3044345454" (removes "(", ")", and "-")
[edit]
Split up a string, expressing the divider as a regular expression
var string3="1,2, 3, 4, 5" parsestring3=string3.split(/\s*,\s*/) //Returns the array ["1","2","3","4","5"]
[edit]
Assign to Groupings and remix initial string
var objRegExp = /(\w+)\s(\w+)/; var strFullName = "Jane Doe"; var strReverseName = strFullName.replace(objRegExp, "$2, $1");
[edit]
Gotchas
- Regex functions generally return values, rather than mutate the original value. To mutate a string, e.g. run a substitution, you'll usually do something like x = x.replace(/so last week/, "new, improved, beta 2.0").
- Remember to use the /g flag for global substitutions. e.g. x.replace(/dirty/g, "clean"). Otherwise, only one dirty will be cleaned.
Time your website with
WebWait - from the creator of AjaxPatterns.org
