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...
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!
const [name, , unit, ...others] = ...
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];
console.log(name);
console.log(street);
Even though this is not the simplest way, you could do this:
var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
keys = "name address1 address2 city state zipcode".split(" "),
address = {};
// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
address[ keys.unshift() ] = match;
});
// address will contain the mapped result
address = {
address1: "123 Street"
address2: "Apt 4"
city: "New York"
name: "john smith"
state: "NY"
zipcode: "12345"
}
Update for ES2015, using destructuring
const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);
// The variables defined above now contain the appropriate information:
console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345
keys
. The second replace function is using [^~]+
to match each different part (i.e. '123 Street', 'Apt 4', etc) and calls the function for each part, passing it as the argument. At each run, the function takes the first key from the keys array (also removing it using Array.unshift) and assigns the key and the part to the address object.
You'll want to look into JavaScript's substr or split, as this is not really a task suited for jQuery.
If Spliter is found then only
it will Split it
else return the same string
function SplitTheString(ResultStr) { if (ResultStr != null) { var SplitChars = '~'; if (ResultStr.indexOf(SplitChars) >= 0) { var DtlStr = ResultStr.split(SplitChars); var name = DtlStr[0]; var street = DtlStr[1]; } } }
split()
method in JavaScript is used to convert a string to an array.
It takes one optional argument, as a character, on which to split. In your case (~).
If splitOn is skipped, it will simply put string as it is on 0th position of an array.
If splitOn is just a “”, then it will convert array of single characters.
So in your case:
var arr = input.split('~');
will get the name at arr[0]
and the street at arr[1]
.
You can read for a more detailed explanation at Split on in JavaScript
well, easiest way would be something like:
var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
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.
str.split();
was not working in Firefox, but this worked both in Chrome and Firefox.
str.split();
works in Firefox and all the major browsers.
Commented
Feb 19, 2017 at 15:15
Something like:
var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
Is probably going to be easiest
split("~")
or split(/~/)
but not split("/~/")
. The latter would only split "John/~/Smith"
and not "John~Smith"
.
Commented
Feb 19, 2017 at 15:09
Zach had this one right.. using his method you could also make a seemingly "multi-dimensional" array.. I created a quick example at JSFiddle http://jsfiddle.net/LcnvJ/2/
// array[0][0] will produce brian
// array[0][1] will produce james
// array[1][0] will produce kevin
// array[1][1] will produce haley
var array = [];
array[0] = "brian,james,doug".split(",");
array[1] = "kevin,haley,steph".split(",");
This string.split("~")[0];
gets things done.
source: String.prototype.split()
Another functional approach using curry and function composition.
So the first thing would be the split function. We want to make this "john smith~123 Street~Apt 4~New York~NY~12345"
into this ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');
So now we can use our specialized splitByTilde
function. Example:
splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
To get the first element we can use the list[0]
operator. Let's build a first
function:
const first = (list) => list[0];
The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final getName
function. Building a compose
function with reduce
:
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
And now using it to compose splitByTilde
and first
functions.
const getName = compose(first, splitByTilde);
let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"
//basic url=http://localhost:58227/ExternalApproval.html?Status=1
var ar= [url,statu] = window.location.href.split("=");
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(',')
This isn't as good as the destructuring answer, but seeing as this question was asked 12 years ago, I decided to give it an answer that also would have worked 12 years ago.
function Record(s) {
var keys = ["name", "address", "address2", "city", "state", "zip"], values = s.split("~"), i
for (i = 0; i<keys.length; i++) {
this[keys[i]] = values[i]
}
}
var record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')
record.name // contains john smith
record.address // contains 123 Street
record.address2 // contains Apt 4
record.city // contains New York
record.state // contains NY
record.zip // contains zip
Use this code --
function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");
}