Wednesday, May 2, 2012

JavaScript: Split a string and store into array

Example 1:
<script type="text/javascript">
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]); 
document.write("
 The second element is  " + mySplitResult[1]); 
</script>
Output 1:
The first element is 1234
The second element is 6789
Example 2:
<script type="text/javascript">
 var cars = 'bmw,audi,honda,chrysler';
 var split_cars = cars.split(',');
 for (var i = 0; i < split_cars.length; i++) {
  document.write(split_cars[i] + '
'); // print all words
 }
</script>
Output 2:
bmw
audi
honda
chrysler

Refer site:
http://www.w3schools.com/jsref/jsref_split.asp
http://www.alexxoid.com/blog/dev/javascript-dev/how-to-explode-the-string-in-javascript.html

1 comment: