Javascript Data Type How to - Get first and rest of string from comma separated values








Question

We would like to know how to get first and rest of string from comma separated values.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w w  w . j  a  va 2s  . c o  m-->
var my_string = "boy, girl, dog, cat";
var splitted = my_string.split(',');
var first_item = splitted.shift();
var rest_of_the_items = splitted.join(',');
document.writeln('First: ' + first_item);
document.writeln('<br/>');
document.writeln('Rest: ' + rest_of_the_items);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: