Best practice: Truthy and falsy values in JavaScript

The following example shows how the types of functions and objects can be used to detect the capability of a web browser. The example shows the detection of the WebRTC functionality in a standard way and then uses the ternary operator and the behaviour of truthy and falsy values to refactor the code. The business logic is written in a self-executing function.
Best practice: Truthy and falsy values in JavaScript weiterlesen

Webseiten-URL ohne Dateinamen mit JavaScript erhalten

Über window.location.href erhält man mit JavaScript die Adresse der aufgerufenen Webseite (z.B. http://localhost:8080/webpage/index.html). Möchte man aber nur den Pfad (z.B. http://localhost:8080/webpage/) haben, kann man folgenden Code einsetzen:

1
2
3
// Given: http://localhost:8080/webpage/index.html
// Output: http://localhost:8080/webpage/
var path = window.location.href.match(/^(http.+\/)[^\/]+$/)[1];

Die vorgestellte Methode hat noch einen Schwachpunkt. Führt man den Code nämlich über „http://localhost:8080/webpage/“ und nicht über „http://localhost:8080/webpage/index.html“ aus, so funktioniert der verwendete reguläre Ausdruck nicht wie gewünscht. Das lässt sich aber mit dem bedingten (ternären) Operator beheben:

1
2
3
// Given: http://localhost:8080/webpage/ OR http://localhost:8080/webpage/index.html
// Output: http://localhost:8080/webpage/
var path = ((window.location.href.match(/^(http.+\/)[^\/]+$/) != null) ? window.location.href.match(/^(http.+\/)[^\/]+$/)[1] : window.location);