How to Split a String into Multiple Variables in JavaScript

How can I parse string in Javascript to split a variable into multiple other variables? For example, if I have the following:

var coolVar = '123-abc-itchy-knee';

How can I split this into four variables, such that:

array[0] is 123
array[1] is ABC

Or alternatively, how can I assign each part of the string to separate variables, like:

var1 == 123  
var2 == ABC 

What is the best way to split a JavaScript string?

I’ve been working with JavaScript for a while, and one of the simplest ways to go about this is by using the split() method.* This is a built-in JavaScript method that lets you split a string into an array based on a specified delimiter. In your case, you can split using the hyphen - as the delimiter. Here’s how:


var coolVar = '123-abc-itchy-knee';

var array = coolVar.split('-'); // Split the string into an array

console.log(array[0]); // Output: 123

console.log(array[1]); // Output: abc

This method is straightforward and easy to understand if you just want to split and parse the string in JavaScript.

Building on that approach, if you want to directly assign the split parts to separate variables, you can use destructuring.* Destructuring assignment is really clean and concise for this task. Here’s an example of how to do it:


var coolVar = '123-abc-itchy-knee';

var [var1, var2, var3, var4] = coolVar.split('-'); // Split and assign

console.log(var1); // Output: 123

console.log(var2); // Output: abc

It’s a great way to parse the string in JavaScript into multiple variables in one line of code. Destructuring makes the code look clean and helps you avoid manually indexing the array.

If you’re looking for more control over what gets extracted, consider using regular expressions.* The match() method can be powerful, especially when you want to capture specific patterns in your string. For example:

var coolVar = '123-abc-itchy-knee';
var matches = coolVar.match(/(\d+)-([a-z]+)/); // Match specific patterns

if (matches) {
    var var1 = matches[1]; // First captured group
    var var2 = matches[2]; // Second captured group

    console.log(var1); // Output: 123
    console.log(var2); // Output: abc
}

Using regex, you can parse the string in JavaScript based on specific patterns, giving you more flexibility in how you split and extract information.