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

2 comments:

  1. Thanks,
    It's worked for me.

    Regards,
    Sardeep

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training in India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete