Unexpected result using string.split ()

3

Given the following code:

   function myFunction() {
        var str = "<tr><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td>td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td></tr><tr><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td></tr>";
        var res = str.split("<tr>");
        var resultado = res.length; //3   
        console.log(resultado);       
    }
    
 myFunction();

I do not understand why the result variable takes the value 3 instead of 2, if I only have two labels of type <tr> .

How could I count the results correctly?

    
asked by Paul 20.08.2017 в 22:11
source

1 answer

13

Why do you get that result?

This is the correct behavior of split() , since the function takes the characters before and after the separation element (in this case <tr> )

You can read about split() in:

Example :

var foo = "bar";
console.log(foo.split("bar"));

While you want to separate by the full string "bar" , split() will take the before the separator and the after the separator , and being this the whole word will return an array with two positions, each of them storing the empty string ("") .

On the problem raised:

For the case where you propose split () return an array with the following three positions:

0:""
1:"<td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td>td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td></tr>"
2 :"<td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td></tr>"

 var str = "<tr><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td>td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td></tr><tr><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td></tr>";
console.log(str.split("<tr>"));
    
 

The first position refers to the previous to the first occurrence of <tr> , which is the empty string .

Therefore, to get as many <tr> tags you must subtract 1 from the array result of split()

var trOcurrencies = str.split("<tr>").length-1;

Another way to solve it:

You can also use a regular expression that matches with the string <tr> and takes into account all occurrences, that is, does not stop when you find the first one. You can express the latter by using the option /g of global matcheo

var str= "<tr><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td>td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td><td>Prueba 1</td></tr><tr><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td><td>Prueba 2</td></tr>";
var trOcurrencies= str.match(/<tr>/g).length;
console.log(trOcurrencies);
    
answered by 20.08.2017 в 22:40