I have this string
'john smith~123 Street~Apt 4~New York~NY~12345'
Using JavaScript, what is the fastest way to parse this into
var name = "john smith"; var street= "123 Street"; //etc...
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);
Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.
With JavaScript’s String.prototype.split
function:
var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc.
According to ECMAScript6 ES6
, the clean way is destructuring arrays:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345'; const [name, street, unit, city, state, zip] = input.split('~'); console.log(name); // john smith console.log(street); // 123 Street console.log(unit); // Apt 4 console.log(city); // New York console.log(state); // NY console.log(zip); // 12345
You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345'; const [name, street, ...others] = input.split('~'); console.log(name); // john smith console.log(street); // 123 Street console.log(others); // ["Apt 4", "New York", "NY", "12345"]
I supposed a read-only reference for values and used the const
declaration.
Enjoy ES6!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With