zhasm
12/30/2010 - 2:01 AM

regular expression snippets in javascript

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);
}