Monday, January 2, 2012

Split A String into Array in JavaScript

We have a String containing numbers separated by , or any other delimiters,and we want to get those numbers collected into an array.Here is the steps

<script type="text/javascript">
var str="20,30,40";
var arr=new Array();
arr=str.split(",");
document.write(arr[2]);
</script>

gives 40 //3rd element

2 comments:

  1. function check()
    {
    var names="apple,ball,cat";
    var arrnames=names.split(",");
    alert(arrnames[0]+":"+arrnames[1]);
    }
    o/p:
    apple:ball
    here i neednt to create arrayobject explicity.

    ReplyDelete
  2. Thats correct,Its just to give the clarity to user that arr is Array() object..

    ReplyDelete