jQuery split

There is no jQuery specific split method for exploding a string, javascript native method split should be used instead

Javascript split method divide a string in smaller parts depending on the needle.

For example we need to split the phrase "There is no jQuery specific explode method, use instead javascript native method split" in order to get the individual words.

<div id="myDiv"></div>

<script type="text/javascript">
$(document).ready(function() {

    var myString = 'There is no jQuery specific explode method, use instead javascript native method split';
    var myArray = myString.split(' ');

    // display the result in myDiv
    for(var i=0;i<myArray.length;i++){
        $('#myDiv').append("<div>arr["+i+"] =>"+myArray[i]+"</div>");
    }
});

</script>

The result of the method split is an array containing the individual words. The needle is a blank space.

arr[0] =>There
arr[1] =>is
arr[2] =>no
arr[3] =>jQuery
arr[4] =>specific
arr[5] =>explode
arr[6] =>method,
arr[7] =>use
arr[8] =>instead
arr[9] =>javascript
arr[10] =>native
arr[11] =>method
arr[12] =>split

Removing multiple spaces before split

What if instead of one space between the words there are many ?

<div id="myDiv"></div>

<script type="text/javascript">
$(document).ready(function() {

    var myString = 'There   is no    jQuery specific explode method,  use instead javascript native method split';
    var myArray = myString.split(' ');

});

</script>

The resulting array will be:

arr[0] =>There
arr[1] =>
arr[2] =>
arr[3] =>is
arr[4] =>no
arr[5] =>
arr[6] =>
arr[7] =>
arr[8] =>jQuery
arr[9] =>specific
arr[10] =>explode
arr[11] =>method,
arr[12] =>
arr[13] =>use
arr[14] =>instead
arr[15] =>javascript
arr[16] =>native
arr[17] =>method
arr[18] =>split

The method adds extra array keys where there are multiple spaces.

We have to remove first the extra spaces and make the split after. We use javascript replace method for this:

<div id="myDiv"></div>

<script type="text/javascript">
$(document).ready(function() {

    var myString = 'There   is no    jQuery specific explode method,  use instead javascript native method split';

    // first remove extra spaces
    myString = myString.replace(/[\s]+/g, ' ');    // g = replace all instances

    // then split the string
    var myArray = myString.split(' ');

});

</script>

\s tells replace method to search for white spaces inside the string ([\f\n\r\t\v\u00A0\u2028\u2029]), g parameter tells to find a global search and replace (for all occurences).

The resulting array will be:

arr[0] =>There
arr[1] =>is
arr[2] =>no
arr[3] =>jQuery
arr[4] =>specific
arr[5] =>explode
arr[6] =>method,
arr[7] =>use
arr[8] =>instead
arr[9] =>javascript
arr[10] =>native
arr[11] =>method
arr[12] =>split