擦除子串并爆炸字符串的功能?

时间:2011-09-05 07:01:07

标签: javascript jquery

我想替换“http://”“https://”“www。”并在“/".

上爆炸网址

例如:http://www.google.com/whatever应该返回google.com

我在这个功能上做得和我知道的一样多:

// Change site's title
function changeTitle(url) { 
    var title = url.replace("http://", ""); // 1
    title = title.replace("https://", ""); // 2
    title = title.replace("www.", ""); // 3
    document.title = title; 
}

但我想在一个单独的函数上完成所有过程,例如:function cleanUrl(url)。我试过这个和变种,但无法使它工作:

// Clean URL
function cleanUrl(url) { 
    var title = url.replace("http://", ""); 
    title = title.replace("https://", ""); 
    title = title.replace("www.", ""); 
}

// Change site's title
function changeTitle(url) { 
    cleanUrl(url);
    document.title = title; 
}

我该怎么办?我也不会爆炸,因为我不知道如何。

5 个答案:

答案 0 :(得分:2)

var url = 'http://www.google.com/whatever';
var domain = url.split('/')[2].replace('www.', '');
alert(domain);   // google.com

答案 1 :(得分:1)

试试这个:

function cleanUrl(url) { 
  var title = url.replace("http://", ""); 
  title = title.replace("https://", ""); 
  title = title.replace("www.", ""); 
  return title;
}


function changeTitle(url) { 
  title = cleanUrl(url);
  document.title = title; 
}

答案 2 :(得分:1)

您应该在cleanUrl函数中添加一个return语句以获取标题:

// Clean URL
function cleanUrl(url) { 
    var title = url.replace("http://", ""); 
    title = title.replace("https://", ""); 
    title = title.replace("www.", ""); 
    return title;
}

// Change site's title
function changeTitle(url) { 
    var title = cleanUrl(url);
    document.title = title; 
}

答案 3 :(得分:1)

// Clean URL
function cleanUrl(url) {
    var title = url.replace("http://", "");
    title = title.replace("https://", "");
    title = title.replace("www.", "");
    var exploded = title.split('/');
    title = exploded[0];
    return title;
}

// Change site's title
function changeTitle(url) {
    title = cleanUrl(url);
    document.title = title;
}

答案 4 :(得分:1)

删除所有启动的http或https或www(如果已定义)并从URL中删除网址路径部分:

// Clean URL
function cleanUrl(url) { 
    return url.replace(/^(http(s)?:\/\/)?(www\.)?([^\/]+)(\/.*)?$/gi,"$4");
}

console.info(cleanUrl('hTTp://google.com/whatever')); // result: google.com
console.info(cleanUrl('htTPs://google.com/whatever')); // result: google.com
console.info(cleanUrl('http://www.google.com/whatever')); // result: google.com
console.info(cleanUrl('https://www.google.com/whatever')); // result: google.com
console.info(cleanUrl('wWW.google.com/whatever')); // result: google.com
console.info(cleanUrl('google.com/whatever')); // result: google.com
console.info(cleanUrl('google.com')); // result: google.com
console.info(cleanUrl('ttt.www.google.com/whatever')); // result: ttt.www.google.com