* 正規表現 [#z654448b]
** 正規表現オブジェクト [#rb92f976]
var re = new RegExp('a');
var re = /a/; // 上の構文糖
console.log(re.test('abc')); // true
console.log(re.exec('abc')); // "a"
なお、文字列リテラル('a')では\はエスケープされるので、例えばnew RegExp('\\d')のように\を重ねる事。正規表現リテラル(/a/)では重ねなくて良い。
** Stringオブジェクトの正規表現関連メソッド [#k0b511f2]
*** match() [#i263eb70]
console.log("123abc456".match(/\d+/g)); // ["123", "456"]
// "123abc456".match('(\\d)','g')も同じ
if ( m = "123abc456".match(/([a-z])/g) ) {
console.log(m); // ["a", "b", "c"]
}
*** replace() [#s99ff54b]
console.log("123abc456".replace(/\d+/,'X')); // Xabc456
var x10 = "123abc456".replace(/\d/g, function (val,pos) {
return val * 10;
});
// x10 "102030abc405060"
// pos [0,1,2,6,7,8]
*** split() [#v099223d]
console.log("a,b:c,,d".split(/[,:]/)); // 他のブラウザ["a", "b", "c", "", "d"]
// IE ["a", "b", "c", "d"]