Converting a string into an array in JavaScript is tricky. The act of changing the string is simple, but if not done properly, you might see errors or even latent errors.
Before diving into errors commonly associated with changing a string into an array, it might be helpful to go into how to create strings and arrays in JavaScript. With these foundations in mind, you should be able to understand better how to convert a string into an array without causing an error.
Let's get to it!
Whether you’re just starting in JavaScript or you’re an expert, you’re most likely familiar with JavaScript strings. They are fundamental in coding. So, we won’t spend too much time on this particular topic. What you need to know is that a JavaScript string stores a series of characters within quotes.
For example:
Let text = ‘Airbrake is Awesome’
Or you can put the exact same string in double-quotes:
Let text = “Airbrake is Awesome”
Next, we’ll provide a quick refresher on what an array is in JavaScript.
If you already know what an array is and you’re comfortable working with arrays, please proceed to the next section, where we’ll go over how to convert strings to arrays.
For those of you who might need a refresher on arrays, here’s a simple definition:
An array in JavaScript uses a single variable to store several elements. It’s perfect when you need to create and store lists.
Here’s an example of an array:
Const A = [“Airbrake”, “ Error Monitoring”, “Debugging”]
You’ll receive the following list when you run this script:
Airbrake, Error Monitoring, Debugging.
And that’s an array!
When working with Data, there are times when we're in control and when we're not. By changing a string into an array, it allows us to take control of certain data points.
For example, maybe we have incorrectly formatted data coming from the API. Perhaps the API might contain a specific character for ‘Airbrake-is-awesome’ that is not required in the final output. For this purpose, we will split the string data by using a delimiter (which we'll go over in the next section) for every occurrence of “-” to get the final output “Airbrake is awesome.”
Or, perhaps, you have a list of strings that you want to call on as an array because, from a data point of view, it makes more sense.
As you can see, strings and arrays serve two different purposes. A string stores characters, while an array creates list-like objects due to its ability to hold more than one value. You might need to convert those strings into an array in some cases. The split() method is the most popular way to do this.
The split() method is one of the most popular ways JavaScript developers convert their strings into arrays. When using a split() within a string, the substring returns as an array.
Here's an example:
Let A = “Airbrake Error Monitoring and Debugger”;
Const split_string = A.split(“ “):
console.log(split_string)
Output = [“Airbrake”, “Error”, “Monitoring”, “and”, “Debugger”]
What just happened here? Why did the A.split(“ “) turn our original string into an array?
This is how the computer program reads the split(): string.split(delimiter, limit)
Let's continue this demostration and use the same example. Let's say the data we get from an API looks like this “Airbrake-is-awesome,” and output should be a string “Airbrake is awesome.”
To accomplish this, we will use the JavaScript string split() method, which accepts a separator as one of the options. Here we will pass the “-” separator telling the split method to look at the string data coming from the API, separate it at every “-” instance and provide the output in an array.
Here we use the string split() method with a separator “-”. The output is an array of strings separated at every instance of “-”. To get our desired string output, we will use the Array join() method to combine each element in the array back into a string without the “-” character.
The delimiter indicates where to split the string. If you decide to leave it empty, JavaScript will automatically default to turning each character into an array. The “limit” is how many times the string should be split. Keep in mind that both of these are optional, but they provide more control over how the string should be split.
In the above example, the string we converted into an array is the one set to “A” and between the double-quotes. You can take it a step further, as well. You can change the delimiter so the program picks up specific areas to convert into an array.
Example:
Let B = “Airbrake, Error, Monitoring, Performance, Debugger”;
Const split_string = B.split(“ , “):
console.log(split_string)
Output = [“Airbrake”, “Error”, “Monitoring”, “Performance”, “Debugger”]
But, if you leave the delimiter empty, like so:
Let C = “Airbrake”;
Const split_string = C.split(“ “); //note that there is no additional space between “ “
console.log(split_string)
The output is:
[“A”, “i”, “r”, ”b” ,”r”, ”a” ,”k”, ”e”]
What happens when you put a limit in? When you put a limit in, you’re limiting how much a string should be listed within your array.
Here’s an example of a limit with 6:
Let D = “Airbrake is an awesome error monitoring and debugging tool”;
Const split_string = D.split(“ “ ,6);
console.log(split_string)
The output will be:
[“Airbrake”, “is”, “an”, “awesome”, “error”, “monitoring”].
The split() method is the best and most common method out there for converting a string into an array.
When switching between strings and arrays, there’s always a chance that you might create an error that could end up in production. Here is a list of errors that might arise and how to fix them if they do:
"Object doesn't support this property or method" or “split is not a function”
JavaScript is a “loosely typed” language. This means that the language will automatically convert data types so the user doesn't have to specify what type of information should be stored in a variable in advance.
For example, a bug in the code where the expected output should be a string “53” but JavaScripts converts into a number type 53. The split() is a string method, so anything besides a string will throw an error. If you try to use a split() method on a number like 53, it will give an error “split is not a function”
Example:
If this error pop-ups for you, it means that your attempt to split() failed and didn’t convert your string to an array. The easiest way to fix this is to return to the split() and fix what’s causing the error.
When using the string split() method, keep an eye out for TypeErrors. TypeErrors occur if the split string is "undefined."
For example, invoking split() method on a variable. If the variable is declared and never assigned a string value, it will be undefined and the TypeError will be thrown by JavaScript.
Example:
Avoid this error by using proper error handling. Before involving the split() method, check for any undefined variables.
Example:
When you go back and manipulate existing code, there’s always a chance that changing one thing can lead to a cascade of errors. This can be true with you convert a string into an array within JavaScript. Ensure that anytime you change existing code, you’ll be able to catch any new errors with an error monitoring software like Airbrake. Airbrake Error & Performance Monitoring will easily find errors associated with changing a string to an array within JavaScript and tell you exactly where the error occurred.
Give it a try! Create a free-forever developer account, which comes with unlimited error and performance events for the first 30 days.