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
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]; } } }
Something like:
var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
Is probably going to be easiest
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('~');
you will get name at arr[0] and street at arr1.
You can read for more detail explanation at Split on in JavaScript
Use this code --
function myFunction() {
var str = "How are you doing today?";
var res = str.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"