I want to replace "http://" "https://" "www." and also explode the url on "/".
For example: http://www.google.com/whatever should return google.com
I was doing as much as I knew how on this function:
// 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;
}
But I want to do all the process on a 开发者_C百科separate function, e.g: function cleanUrl(url)
. I tried this and variants but couldn't make it work:
// 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;
}
How do I do it? Also I'm not exploding the url since I didn't know how.
var url = 'http://www.google.com/whatever';
var domain = url.split('/')[2].replace('www.', '');
alert(domain); // google.com
// 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;
}
Try this:
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;
}
You should add a return statement at cleanUrl function in order to get the title:
// 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;
}
This remove all starting http or https or www (if defined) and remove url path part from 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
精彩评论