How to explode or split a string in JavaScript

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript split() method

If you want to explode or split a string from a certain character or separator you can use the JavaScript split() method. The following example will show you how to split a string from whitespace. The returned value will be an array, containing the splitted values.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>JavaScript Split a String from Space</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  • <script type="text/javascript">
  •     function splitArray(){
  •         var myStr = "quick brown fox";
  •         var strArray = myStr.split(" ");
  •         
  •         // Display array values on page
  •         for(var i = 0; i < strArray.length; i++){
  •             $("body").append("<p>" + strArray[i] + "</p>");
  •         }
  •     }
  • </script>
  • </head> 
  • <body>
  •     <p>Click the following button to split myStr string and show returned array values using for loop</p>
  •     <button type="button" onclick="splitArray();">Show Splitted Values</button>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.