🍦 JavaScript - Regex
Updated at 2013-04-08 12:42
There are two ways to create regular expression variable. Prefer shorter syntax / /
if possible.
var rule = new RegExp('test');
var rule = /test/;
Basic regular expression syntax.
var rule = /[pb]attern/; // match in set
var rule = /[^acd]attern/ // match not in set
var rule = /pa[t]{2}rn/ // count
var rule = /pattern?/ // 0 or 1
var rule = /pattern*/ // 0 or more
var rule = /pattern+/ // 1 or more
var rule = /pattern/i // incase-sensitive matching
var rule = /pattern/g // match all, not just first
var rule = /pattern/m // multiline
Check for matches in a string.
var rule = /test/;
rule.test('Is this a test?');
// => true
Split using regex.
var rule = /test/;
'Is this a test or not a test?'.split(rule);
// => ['Is this a ', ' or not a ', '?']
Replace first that regex matches.
var rule = /test/;
'Is this a test or not a test?'.replace(rule, 'hoot');
// => 'Is this a hoot or not a test?'
Replace all that regex matches.
var rule = /test/g;
'Is this a test or not a test?'.replace(rule, 'hoot');
// => 'Is this a hoot or not a hoot?'