Convert string into array JavaScript
In this post, you will learn how to convert a string into an array using the JavaScript programming.
Sometimes in the development process, we may face a situation where we need to convert a string into an array. There are lots of ways to achieve this task in JavaScript. Here, we have mentioned most of them.
Converting string to array using split() method
The split() method splits a string into an array of substrings. It returns the new array. The split() method does not change the original string. Syntax-
string.split(separator, limit)
- separator- Optional, the string will be split based on this value. Optional, the string will be split based on this value. An array with the original string is returned in case it is empty.
- limit- Optional, an integer value indicating how many times the string needs to be split.
Example 1
The given JavaScript program splits the given string into an array of strings by separating it into substrings.
let str1 = "There is nothing impossible to they who will try";
const split_string = str1.split(" ");
console.log(split_string)
Output of the above code:
[ 'There',
'is',
'nothing',
'impossible',
'to',
'they',
'who',
'will',
'try' ]
Example 2
let stringArray = "Spread-love-everywhere-you-go";
let array = stringArray.split("-")
console.log(array);
Output of the above code:
[ 'Spread', 'love', 'everywhere', 'you', 'go' ]
Related Articles
Generate random numbers in JavaScriptJavascript window location
Remove duplicates from array Javascript
Scientific calculator JavaScript
How to reverse string in Javascript
JavaScript display PDF in the browser using Ajax call
Parsing JSON in Javascript
Javascript speech recognition example
Select/deselect all checkboxes using Javascript
Print specific part of a web page in javascript
Dynamically Add/Delete HTML Table Rows Using Javascript
jQuery Ajax serialize form data example
Image popup on page load using HTML and jQuery
Ajax live data search using jQuery PHP MySQL
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jquery image zoom on mouseover example
Bootstrap star rating input example
Bootstrap datepicker example
Submit a form data without page refresh