Split "100000000000" in JQUERY

Asked

Viewed 105 times

1

I need to separate all the characters of a string into an array, and I have a problem, my code is the following

var PISCampos = campos.split(""); 

When sending fields in the variable the following string: "011001000000". Everything works, and I tested with others like "000001000000" and the split works perfectly

But using this string: "100000000000" the split does not work. I put an alert on the top line and one on the bottom line, only the first one works with this string, suggesting that the error is right there. The first alert displays the fields variable, and its value is correct.

TEST CODE

alert(campos);
var PISCampos = campos.split("");
alert("teste");

THE PROBLEM

I used it to recover the value I told them ("011001000000")

$("#campo option:selected" ).data("campos")

And my HTML was like this

    <option data-campos="100000000000" value="53">Bla Bla Bla</option>

Only from what I realized, since the first character was a nonnull number, the val() of the jquery considered it an integer, my fault, my sincere apologies.

SOLUTION

campos = campos.toString();
var PISCampos = campos.split("");
  • Put the test code too, it is easier to locate the problem. A [mcve] is fundamental to this type of doubt.

  • the problem is probably not in the string. See here: https://jsfiddle.net/z09zxar9/ (open the console) vc is not sending an int, as in the last case? This would explain.

  • Did not allow to reproduce this error. See: http://codepen.io/bacco/pen/vXQqAN

  • Your test doesn’t run. It doesn’t have any of the numbers you mentioned in it. I suggest re-reading what a [mcve].

  • Now I understand the problem, I’ll make an issue and explain

  • 1

    When it comes to HTML, "53" does not mean that 53 is a string as it would in a programming language. This way, when you take this value, it will go as 53, and you should deal with whether it is a string or not. If you use a unique function of a String type, you better ensure that the input is a String : String(campos) or campos.toString(), this way you guarantee that you will not have this problem

  • Yes Lucas, I used toString(), thank you very much

Show 2 more comments

1 answer

3


It was supposed to work, split is a function of the String class.

That works:

var campos = "100000000000";
var PISCampos = campos.split("");

PISCampos.forEach(function(e){alert(e)}); // Somente para mostrar

That doesn’t work:

var campos = 100000000000;
var PISCampos = campos.split("");

PISCampos.forEach(function(e){alert(e)}); // Somente para mostrar

Check that the variable you are passing is a String, and try using a console to see if you are printing any Javascript errors (Chrome dev console or Firebug for Mozilla).

Jsfiddle working

Browser other questions tagged

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