【问题标题】:Detect Duplicate URL for domain names using javascript使用 javascript 检测域名的重复 URL
【发布时间】:2012-06-02 13:30:56
【问题描述】:

我想编写一个检查重复 url 的代码,但简单的字符串匹配不起作用,例如string1 == string2。以以下网址为例:

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

【问题讨论】:

  • 这是四个不同的 URL。前两个是相对的(因此必须使用基本 URL 解析)。最后两个可能具有相同的内容,或者一个可能重定向到另一个,或者它们可能具有不同的内容。您不能安全地假设内容是相同的。

标签: javascript url dns


【解决方案1】:
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"

【讨论】:

  • ohhhk thnx 但我怀疑它是否适用于这种模式 http:facebook.com 中的 URL ..我知道 'http://' 是这种格式,但是在 URL 栏中输入时它确实接受并且解析到 www.facebook.com
  • @Zohaib 只需将"http:" 附加到patterns 即可处理这种格式
  • 哦,是的,谢谢。因此,要完全依赖这种方法,我需要检查哪些格式会出现,以便我可以处理模式数组中的这些模式。
【解决方案2】:

如何使用 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

【讨论】:

    猜你喜欢
    • 2014-02-11
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    相关资源
    最近更新 更多