2

重複するURLのチェックをコーディングしたいのですが、単純な文字列の一致は機能しませんstring1 == string2。例として次のURLを考えてみましょう。

  1. www.facebook.com/authorProfile
  2. facebook.com/authorProfile
  3. http://www.facebook.com/authorProfile
  4. http://facebook.com/authorProfile
4

2 に答える 2

2
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"
于 2012-05-28T06:42:38.247 に答える
0

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
于 2012-05-28T08:03:46.410 に答える