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

JavascriptString Split

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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!

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

well, easiest way would be something like:

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

Something like:

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

Is probably going to be easiest

Solution 11 - Javascript

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

Solution 12 - Javascript

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"

Solution 13 - Javascript

Try in Plain Javascript

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

 var ar= [url,statu] = window.location.href.split("=");

Solution 14 - Javascript

JavaScript: Convert String to Array JavaScript Split

    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."
 
    var result = str.split('-'); 
     
    console.log(result);
     
    document.getElementById("show").innerHTML = result; 

<html>
<head>
<title>How do you split a string, breaking at a particular character in javascript?</title>
</head>
<body>
 
<p id="show"></p> 
 
</body>
</html>

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

Solution 15 - Javascript

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

Solution 16 - 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

Solution 17 - Javascript

Use this code --

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionctrlShiftBryanView Question on Stackoverflow
Solution 1 - JavascriptZachView Answer on Stackoverflow
Solution 2 - JavascriptVahid HallajiView Answer on Stackoverflow
Solution 3 - JavascriptGrant WagnerView Answer on Stackoverflow
Solution 4 - JavascriptTorsten WalterView Answer on Stackoverflow
Solution 5 - JavascriptJohn SheehanView Answer on Stackoverflow
Solution 6 - JavascriptBJ PatelView Answer on Stackoverflow
Solution 7 - JavascriptDanView Answer on Stackoverflow
Solution 8 - JavascriptTusharView Answer on Stackoverflow
Solution 9 - JavascriptAnkit21ksView Answer on Stackoverflow
Solution 10 - JavascriptSteve gView Answer on Stackoverflow
Solution 11 - JavascriptBilly HallmanView Answer on Stackoverflow
Solution 12 - JavascriptimtkView Answer on Stackoverflow
Solution 13 - JavascriptHari LakkakulaView Answer on Stackoverflow
Solution 14 - JavascriptDeveloperView Answer on Stackoverflow
Solution 15 - JavascriptChris BartholomewView Answer on Stackoverflow
Solution 16 - JavascriptPHP GuruView Answer on Stackoverflow
Solution 17 - JavascriptBal mukund kumarView Answer on Stackoverflow