Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 250
Maciek Semik Avatar asked Feb 08 '23 23:02

Maciek Semik


1 Answers

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

like image 192
charlietfl Avatar answered Feb 11 '23 15:02

charlietfl