The code looks better (more readable) if you look at the 4 characters at once:
if(string.substr(0, 4) === "www.") {
}
Or
if(string.substring(0, 4) === "www.") {
}
The two methods do basically the same thing, but the first receives the initial index and the length, while the second receives the initial index and the final (not inclusive).
One more method, which receives two indices and extracts until before the final index:
if(string.slice(0, 4) === "www.") {
}
In terms of performance, the 3 methods seem equivalent (in V8/Chrome).
In addition to these three, there is also testing via regular expression, such as suggested by Qmechanic73, and the indexOf
, suggested by Sergio. It is still possible to take other paths, such as comparing each character by getting them via String.prototype.charAt
.
Comparing to this type of solution, its original test, which checks each individual character, is much faster than any other (in my browser). It surprised me. By quickly comparing the extraction methods in the language specification, I saw no obvious reason for this. Probably the culprit for the delay of the other methods is the creation of a wrapper Object of the kind String
, and subsequent method call in that object (including verification of the prototype chain).
string.substring(0, 4) == "www."
– Caffé