628

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...
user1725145
  • 3,993
  • 2
  • 37
  • 58
ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78

16 Answers16

982

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.
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Zach
  • 24,496
  • 9
  • 43
  • 50
93

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!

manuell
  • 7,528
  • 5
  • 31
  • 58
Vahid Hallaji
  • 7,159
  • 5
  • 42
  • 51
55

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);
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Grant Wagner
  • 25,263
  • 7
  • 54
  • 64
  • 65
    You don't need to add regex to this simple replace. It will only make it slower if anything. You can change it to quotation marks for a simple string replace. – Anish Gupta Aug 14 '12 at 11:05
17

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
Torsten Walter
  • 5,614
  • 23
  • 26
  • 4
    first we have a string seperated by '~' signs and an array of `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. – ewino Jan 05 '15 at 09:52
14

You'll want to look into JavaScript's substr or split, as this is not really a task suited for jQuery.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • substr is now deprecated, so better to use substring() [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring] – Sashini Hettiarachchi Aug 17 '22 at 16:15
8

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];
        }
    }
}
BJ Patel
  • 6,148
  • 11
  • 47
  • 81
7

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

Ankit21ks
  • 468
  • 1
  • 7
  • 22
5

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    This worked for me! `str.split();` was not working in Firefox, but this worked both in Chrome and Firefox. – Sandeep May 17 '16 at 12:12
  • 1
    @Sandeep, no, `str.split();` [works in Firefox and all the major browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split). – Andrew Willems Feb 19 '17 at 15:15
5

well, easiest way would be something like:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
Dan
  • 61,568
  • 9
  • 61
  • 78
3

Something like:

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

Is probably going to be easiest

Steve g
  • 2,471
  • 17
  • 16
  • 3
    No, you want either `split("~")` or `split(/~/)` but not `split("/~/")`. The latter would only split `"John/~/Smith"` and not `"John~Smith"`. – Andrew Willems Feb 19 '17 at 15:09
2

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(",");
2

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"
imtk
  • 1,510
  • 4
  • 18
  • 31
2

Try in Plain Javascript

 //basic url=http://localhost:58227/ExternalApproval.html?Status=1

 var ar= [url,statu] = window.location.href.split("=");
Community
  • 1
  • 1
Hari Lakkakula
  • 199
  • 1
  • 4
1

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(',')
Chris Bartholomew
  • 1,000
  • 6
  • 7
0

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
PHP Guru
  • 1,301
  • 11
  • 20
-2

Use this code --

function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133