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
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!
Since the splitting on commas question is duplicated to this question, adding this here.
If you want to split on a character and also handle extra whitespace that might follow that character, which often happens with commas, you can use replace
then split
, like this:
var items = string.replace(/,\s+/, ",").split(',')
You don't need jQuery.
var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];
//basic url=http://localhost:58227/ExternalApproval.html?Status=1
var ar= [url,statu] = window.location.href.split("=");
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.
You can use split
to split the text.
As an alternative, you can also use match
as follow
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';
matches = str.match(/[^~]+/g);
console.log(matches);
document.write(matches);
The regex [^~]+
will match all the characters except ~
and return the matches in an array. You can then extract the matches from it.