How to check if the first four characters of a string match 'www.'?

Asked

Viewed 4,731 times

12

What is the best way to verify this? More simply and with better performance.

I could only imagine doing so:

var string = "www.google.com";

if(string[0] == "w" && string[1] == "w" && string[2] == "w" && string[3] == "."){
   // string começa com www.
}
  • 7

    string.substring(0, 4) == "www."

4 answers

18


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

  • If the string does not have the minimum size expected (suppose it is only "ww") the original OP code will fail, right? And in the case of each of these methods, how is treated the out of Bounds in Javascript...? If they are robust, it is one more benefit of this use.

  • No error trying to access an index that does not exist in the string, simply returns undefined @Luizvieira.

9

Another alternative is the method RegExp.test

var endereco = "www.google.com";

if (/^www\./.test(endereco))
    console.log("Começa com www.");
else
    console.log("Não começa com www.");

The expression ^www\. will match the characters www. at the beginning of string. About the performance, the code posted in the question seems to be the fastest, as can be seen in this comparative created by @bfavaretto.

  • Faster probably by not having to create a copy of part of the string every time, as should occur with the substring. It would be nice to compare with @Sergio’s method - I suppose it also does not create copy of the string and the code is simpler than the original AP.

  • @Caffé There is a copy of part of the string. What does not exist is the creation of a type object String so that the methods can be invoked (see my updated response for more details).

6

Another variant still not referenced to check if the string starts with these 4 characters:

if (string.indexOf("www.") == 0) // caso sim
else // caso não

The .indexOf() checks the position of "www." in the variable string. If the result of .indexOf(), was 0 then the string starts with "www.".

3

What @Qmechanic73 said is correct, although its code seems a little more extensive it and faster than the others, just a simple tip to improve a little performance, use === instead of ==.

See the difference in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Igualdade

To performance varies per browser, in firefox the == was faster than the === and on google ===. The difference is that the == type conversion. For example:

1 == '1': true
1 === '1': false

How you use string comparing with string does not need to convert type would be:

'w' === 'w': true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.