これはなに
JavaScriptの正規表現でNamed Captureを使えるようにします。
手抜きなのでString#match,String#replace,RegExp#testのみサポート。
ダウンロード
namedcapture.js
サンプル
実行
var reg_url = /(
http|https):\/\/(
[^\/]*?)\/(
.*)/; alert(reg_url); // この状態だとマッチしません reg_url = reg_url.support_capture(); alert(reg_url); // <>の部分を無視して再コンパイルします alert(reg_url.captureNames); // protocol,domain,path var result = "http://example.com/index.html".match(reg_url); // 通常のmatchと同様に結果を配列として使えますが alert(result); // プロパティにも格納されてるのでハッシュとして使えます alert([ "protocol = " + result.protocol, "domain = " + result.domain, "path = " + result.path ].join("\n"));
実行
// ドメインの部分だけ大文字にする var reg_url = /(
http|https):\/\/(
[^\/]*?)\/(
.*)/; var res = "http://example.com/index.html".replace(reg_url,function(m){ return m.replace(m.domain,m.domain.toUpperCase()); }); alert(res); // こっちのほうがわかりやすいよなあ var res = "http://example.com/index.html".replace(reg_url,function($0,protocol,domain,path){ return $0.replace(domain,domain.toUpperCase()); }); alert(res);
実行
var reg_url = /(
http|https):\/\/(
[^\/]*?)\/(
.*)/; alert(reg_url.test("http://example.com/index.html")); // マッチするかどうか調べます alert(RegExp.last_match.domain); // RegExp.last_matchに保持しています。