Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created December 30, 2010 02:01
Show Gist options
  • Save zhasm/759359 to your computer and use it in GitHub Desktop.
Save zhasm/759359 to your computer and use it in GitHub Desktop.
regular expression snippets in javascript
//if match
if (subject.match(/abc/)) {
// Successful match
} else {
// Match attempt failed
}
//get all match
result = subject.match(/regex/g);
//object match test
var myregexp = /regex/i;
var match = myregexp.exec(subject);
if (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
} else {
// Match attempt failed
}
//iterate over all match in a string
var match = myregexp.exec(subject);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
match = myregexp.exec(subject);
}
//iterate over all matches and capturing groups in a string
var myregexp = /regex/ig;
var match = myregexp.exec(subject);
while (match != null) {
for (var i = 0; i < match.length; i++) {
// matched text: match[i]
}
match = myregexp.exec(subject);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment