/usr/portage

Lazy, object-oriented URL parsing in JavaScript 2

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«.

Filed under , & two comments & no trackbacks

Trackbacks

Trackback specific URI for this entry

No Trackbacks

Comments

  1. mawa says:
    published on December 3rd 2006, 08:02:31 am *

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

    Reply

  2. Lars Strojny replys:
    published on December 3rd 2006, 02:53:18 pm *

    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.

    Reply

Add a Comment & let me know what you think