最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - regex strip domain name - Stack Overflow

programmeradmin3浏览0评论

A quick simple regex question

I have a domain name in a string that I need to strip - There is always http://www. and the domain always ends in "/"

g_adv_fullpath_old = g_adv_fullpath_old.replace(/http\:\/\/www\.(.*?)\//ig, '');

how do I create the regex to strip the domain name?

Any help would be appreciated

A quick simple regex question

I have a domain name in a string that I need to strip - There is always http://www. and the domain always ends in "/"

g_adv_fullpath_old = g_adv_fullpath_old.replace(/http\:\/\/www\.(.*?)\//ig, '');

how do I create the regex to strip the domain name?

Any help would be appreciated

Share Improve this question edited Feb 28, 2011 at 22:46 mellamokb 56.8k12 gold badges110 silver badges138 bronze badges asked Feb 28, 2011 at 22:43 Gerald FerreiraGerald Ferreira 1,3372 gold badges23 silver badges44 bronze badges 2
  • do you want to replace the domain name with an empty string? – Rian Schmits Commented Feb 28, 2011 at 22:48
  • the ':' doesn't need to be escaped by the way – Rian Schmits Commented Feb 28, 2011 at 23:03
Add a ment  | 

4 Answers 4

Reset to default 9

I would simply split on "/". For example:

>>> "http://www.asdf./a/b/c".split("/").slice(3).join("/")
'a/b/c'

Why plications? Simple indexOf will do.
First remove http://www (10 characters), then everything before the first slash.

var s = "http://www.google./test";
s = s.substr(10);
s = s.substr(s.indexOf('/'));
alert(s);

Or split, as David suggests.

An example

If you are looking to remove the http://www. and the following slash (plus anything after it) Try:

g_adv_fullpath_old.replace(/http:\/\/www\.(.*?)\/.*/ig, '$1')

You can also extend the stringobject so it supports urlParts

Example

http://jsfiddle/stofke/Uwdha/

Javascript

String.prototype.urlParts = function() {
    var loc = this;
    loc = loc.split(/([a-z0-9_\-]{1,5}:\/\/)?(([a-z0-9_\-]{1,}):([a-z0-9_\-]{1,})\@)?((www\.)|([a-z0-9_\-]{1,}\.)+)?([a-z0-9_\-]{3,})((\.[a-z]{2,4})(:(\d{1,5}))?)(\/([a-z0-9_\-]{1,}\/)+)?([a-z0-9_\-]{1,})?(\.[a-z]{2,})?(\?)?(((\&)?[a-z0-9_\-]{1,}(\=[a-z0-9_\-]{1,})?)+)?/g);
    loc.href = this;
    loc.protocol = loc[1];
    loc.user = loc[3];
    loc.password = loc[4];
    loc.subdomain = loc[5];
    loc.domain = loc[8];
    loc.domainextension = loc[10];
    loc.port = loc[12];
    loc.path = loc[13];
    loc.file = loc[15];
    loc.filetype = loc[16];
    loc.query = loc[18];
    loc.anchor = loc[22];
    //return the final object
    return loc;
};

Usage:

 var link = "http://myusername:[email protected]/a/b/c/index.php?test1=5&test2=789#tite";
 var path = link.urlParts().path;
 var path = link.urlParts().user;
发布评论

评论列表(0)

  1. 暂无评论