重複するURLのチェックをコーディングしたいのですが、単純な文字列の一致は機能しませんstring1 == string2
。例として次のURLを考えてみましょう。
- www.facebook.com/authorProfile
- facebook.com/authorProfile
- http://www.facebook.com/authorProfile
- http://facebook.com/authorProfile
重複するURLのチェックをコーディングしたいのですが、単純な文字列の一致は機能しませんstring1 == string2
。例として次のURLを考えてみましょう。
function extract(str){
var patterns = [
"http://www.",
"http://",
"www."
];
for(var i=0, len=patterns.length; i < len; i++){
var pattern = patterns[i];
if(str.indexOf(pattern) == 0)
return str.substring(pattern.length);
}
return str;
}
これにより、これらすべてのリンクがfacebook.com/authorProfile
スタイルに変換され、比較できるようになります。
links = [
"www.facebook.com/authorProfile",
"facebook.com/authorProfile",
"http://www.facebook.com/authorProfile",
"http://facebook.com/authorProfile"
];
for(var i=0, len=links.length; i<len; i++){
console.log( extract(links[i]) );
}
// will produce 4 "facebook.com/authorProfile"
javascript正規表現を使用するのはどうですか?基本的に、http://とwwwを削除します。
.replace(/www.|http:\/\//g, '');
例:
var s1 = 'www.facebook.com/authorProfile';
var s2 = 'facebook.com/authorProfile';
var s3 = 'http://www.facebook.com/authorProfile';
var s4 = 'http://facebook.com/authorProfile';
s1.replace(/www.|http:\/\//g, '');
s2.replace(/www.|http:\/\//g, '');
s3.replace(/www.|http:\/\//g, '');
s4.replace(/www.|http:\/\//g, '');
すべてが次のようになります。
facebook.com/authorProfile