2

Lazy, object-oriented URL parsing in JavaScript

published on 2006|12|03

Use this (no, the regexp does not check for RFC-compatibility):

My_Url = function()
{}

My_Url.parse = function(url)
{ this.url = url result = this.url.match(this.regexp) this.scheme = result1 this.host = result2 this.port = result3 this.path = result4 return this
}

My_Url.prototype.parse = My_Url.parse
My_Url.prototype.regexp = /(https?:\/\/)([a-zA-Z0-9_\-\.]+)(:[0-9]+)?\/?(.*)?/

url = new My_Url()
url.parse(‘http://foobar.com/foo’)
alert(url.host)

This will open an alert window with the content »foobar.com«.

Tags: ,

Comments

Show comments linear or threaded

mawa reckons:
published on 2006|12|03, 08:02h
*

Auf RFC-Compliance prüfen würde wahrscheinlich auch einen mehrere tausend Zeichen langen Regexp bedeuten, wenn man nach dem Beispiel im Buch geht.

Lars Strojny reckons:
published on 2006|12|03, 14:53h
*

Ja, genau das ist das Problem. Man muss sowas halt machen, wenn man überprüft, ob eine User-submitted URL auch wirklich eine ist, allerdings wenn es darum geht, dass ein Dispatcher anhand document.URL entscheidet, welchen WritingAdapter er wählt, dann ist das wurscht.

Add comment


Textile-formatting allowed
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
Pavatar/Gravatar/Favatar/MyBlogLog author images supported.