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

后端 未结 17 2391
误落风尘
误落风尘 2020-11-21 05:07

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



        
17条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 05:45

    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"
    

提交回复
热议问题