The code looks better (more readable) if you look at the 4 characters at a time:
if(string.substr(0, 4) === "www.") {
}
Or
if(string.substring(0, 4) === "www.") {
}
The two methods do basically the same thing, however the first one receives the initial index and the length, while the second receives the initial index and the final index (not inclusive).
Another method, which receives two indexes and extracts even before the final index:
if(string.slice(0, 4) === "www.") {
}
In terms of performance, all 3 methods seem equivalent (in V8 / Chrome).
In addition to these three, there is also the regular expression test, such as suggested by QMechanic73 , and indexOf
, suggested by Sergio . It is still possible to take other paths, such as comparing each character and obtaining them via String.prototype.charAt
.
Comparing with this type of solution, your original test, which checks for each individual character, is much faster
a> than any other (in my browser). That 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 other methods is the creation of an wrapper object of type
String
, and later method call on that object (including verification of
String of Prototypes ).