Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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... 
like image 968
ctrlShiftBryan Avatar asked Sep 18 '08 20:09

ctrlShiftBryan


People also ask

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you break a string in words?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);

How do you split a string into elements?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.


2 Answers

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. 
like image 134
Zach Avatar answered Sep 20 '22 15:09

Zach


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!

like image 42
Vahid Hallaji Avatar answered Sep 20 '22 15:09

Vahid Hallaji