[javascript] How do I split a string, breaking at a particular character?

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...

This question is related to javascript string-split

The answer is


well, easiest way would be something like:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]

JavaScript: Convert String to Array JavaScript Split

_x000D_
_x000D_
    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."_x000D_
 _x000D_
    var result = str.split('-'); _x000D_
     _x000D_
    console.log(result);_x000D_
     _x000D_
    document.getElementById("show").innerHTML = result; 
_x000D_
<html>_x000D_
<head>_x000D_
<title>How do you split a string, breaking at a particular character in javascript?</title>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<p id="show"></p> _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/


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


Try in Plain Javascript

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

 var ar= [url,statu] = window.location.href.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];

Use this code --

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

}

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


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

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];

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'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

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];
        }
    }
}

According to ECMAScript6 ES6, the clean way is destructuring arrays:

_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, unit, city, state, zip] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(unit); // Apt 4_x000D_
console.log(city); // New York_x000D_
console.log(state); // NY_x000D_
console.log(zip); // 12345
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, ...others] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
_x000D_
_x000D_
_x000D_

I supposed a read-only reference for values and used the const declaration.

Enjoy ES6!


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

well, easiest way would be something like:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]

Use this code --

function myFunction() {
var str = "How are you doing today?";
var res = str.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

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"

Something like:

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

Is probably going to be easiest


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(',')

well, easiest way would be something like:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[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


You can use split to split the text.

As an alternative, you can also use match as follow

_x000D_
_x000D_
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
matches = str.match(/[^~]+/g);_x000D_
_x000D_
console.log(matches);_x000D_
document.write(matches);
_x000D_
_x000D_
_x000D_

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.


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];

If Spliter is found then only

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];
        }
    }
}

According to ECMAScript6 ES6, the clean way is destructuring arrays:

_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, unit, city, state, zip] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(unit); // Apt 4_x000D_
console.log(city); // New York_x000D_
console.log(state); // NY_x000D_
console.log(zip); // 12345
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, ...others] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
_x000D_
_x000D_
_x000D_

I supposed a read-only reference for values and used the const declaration.

Enjoy ES6!


Something like:

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

Is probably going to be easiest


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

Something like:

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

Is probably going to be easiest


You can use split to split the text.

As an alternative, you can also use match as follow

_x000D_
_x000D_
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
matches = str.match(/[^~]+/g);_x000D_
_x000D_
console.log(matches);_x000D_
document.write(matches);
_x000D_
_x000D_
_x000D_

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.


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

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


JavaScript: Convert String to Array JavaScript Split

_x000D_
_x000D_
    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."_x000D_
 _x000D_
    var result = str.split('-'); _x000D_
     _x000D_
    console.log(result);_x000D_
     _x000D_
    document.getElementById("show").innerHTML = result; 
_x000D_
<html>_x000D_
<head>_x000D_
<title>How do you split a string, breaking at a particular character in javascript?</title>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<p id="show"></p> _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/


Something like:

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

Is probably going to be easiest


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"

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


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];