- 追加された行はこの色です。
- 削除された行はこの色です。
* 正規表現 [#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')も同じ
** "文字列".search() [#h1e9ac88]
ポジションを取り出す。
console.log("123abc456".search(/a/)); // 3
console.log("123abc456".search('x')); // -1
if ( m = "123abc456".match(/([a-z])/g) ) {
console.log(m); // ["a", "b", "c"]
}
** "文字列".match() [#i263eb70]
マッチした文字列を取り出す。
*** 通常 [#vf49beac]
console.log("123abc456".match("[a-z]")) // "a"
*** gスイッチ付き [#l3a46537]
console.log("123abc456".match("[a-z]", "g")) // ["a", "b", "c"]
*** replace() [#s99ff54b]
console.log("123abc456".replace(/\d+/,'X')); // Xabc456
** REGEX.exec() [#h9b32cf3]
マッチした文字列を取り出す。
*** 通常 [#q062c3e5]
var re = /[a-z]/;
console.log(re.exec("123abc456")); // "a"
console.log(re.exec("123abc456")); // "a"
*** gスイッチ付き [#v85d62e9]
var reg = /[a-z]/g;
console.log(reg.exec("123abc456")); // "a"
console.log(reg.exec("123abc456")); // "b"
console.log(reg.exec("123abc456")); // "c"
console.log(reg.exec("123abc456")); // null
var x10 = "123abc456".replace(/\d/g, function (val,pos) {
return val * 10;
});
// x10 "102030abc405060"
// pos [0,1,2,6,7,8]
** "文字列".replace() [#s99ff54b]
文字列を置換する。
console.log("123abc456".replace(/\d+/,'X')); // "Xabc456"
console.log("123abc456".replace(/\d+/g,'X')); // "XabcX"
console.log(
"123abc456".replace(/[a-z]/g, function (val,pos) {
return "[" + val + ":" + pos + "]";
})
);
// 123[a:3][b:4][c:5]456
*** split() [#v099223d]
console.log("a,b:c,,d".split(/[,:]/)); // 他のブラウザ["a", "b", "c", "", "d"]
// IE ["a", "b", "c", "d"]