Maciek
Maciek

Reputation: 1982

Javascript Split wont work when there are no characters to split

HTML

<div id="code1" data-code="123;12"></div>
<div id="code2" data-code="231"></div>

Jquery/Javascript

alert($("#code1").data("code").split(";")[0]);
alert($("#code2").data("code").split(";")[0]);
alert('test');

Since code2 does not have a ";", the code stops working all together. The last alert will not work nor will any code after the non-splitable code. How can I split code by ";" even when it may not have the ";" character?

Upvotes: 4

Views: 822

Answers (2)

charlietfl
charlietfl

Reputation: 171679

data() will typecast a value to number if it is numeric

Try:

$("#code2").data("code").toString().split(';')

More about typecasting in the html 5 attributes section of data() docs

Upvotes: 4

Patrick Roberts
Patrick Roberts

Reputation: 51856

Use the following:

alert($("#code1").attr("data-code").split(";")[0]);
alert($("#code2").attr("data-code").split(";")[0]);
alert('test');

The reason that the second line fails is because the value is implicitly typecasted to a number by jQuery when using $.data. It has nothing to do with the implementation of String.prototype.split, since that returns an array with the 0th element being the full string if the delimiter does not exist.

In order to fix the problem, use $.attr instead of $.data to ensure that jQuery does not internally typecast the value to another type if it looks like another type.

Test on JSFiddle.

Upvotes: 4

Related Questions