次のような文字列があります。
http://x.com/xyz/2013/01/16/zz/040800.php
次のように、そこから2つの文字列を取得したい:
2013-01-16 <-- string 1
04:08:00 <-- string 2
どうやってやるの?
次のような文字列があります。
http://x.com/xyz/2013/01/16/zz/040800.php
次のように、そこから2つの文字列を取得したい:
2013-01-16 <-- string 1
04:08:00 <-- string 2
どうやってやるの?
正規表現を使用できます。サンプル ソリューションは次のとおりです。
var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
result = parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"
これは、ドメインが.com
で、日付の前に追加のパラメータが 1 つだけある場合に機能します。
正規表現について説明します。
/ //starts the regular expression
.com //matches .com
\/ //matches /
[^\/]+ //matches anything except /
\/ //matches a single /
(\d+) //matches more digits (one or more)
\/ //matches /
(\d+) //matches more digits (one or more)
\/ //matches /
(\d+) //matches more digits (one or more)
/ //ends the regular expression
データ全体を抽出する方法は次のとおりです。
var parts = (/.com\/[^\/]+\/(\d+)\/(\d+)\/(\d+)\/[^\/]+\/(\d+)/g).exec('http://x.com/xyz/2013/01/16/zz/040800.php'),
part2 = parts[4];
parts[1] + '-' + parts[2] + '-' + parts[3]; //"2013-01-16"
part2[0] + part2[1] + ':' + part2[2] + part2[3] + ':' + part2[4] + part2[5];
URLが常に同じ形式の場合は、これを実行します
var string = 'http://x.com/xyz/2013/01/16/zz/040800.php';
var parts = string.split('/');
var string1 = parts[4] +'-' +parts[5] +"-" +parts[6];
var string2 = parts[8][0]+parts[8][1] +":" +parts[8][2]+parts[8][3] +":" +parts[8][4]+parts[8][5];
alert(string1);
alert(string2);