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

后端 未结 17 2434
误落风尘
误落风尘 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:41

    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];
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:43

    Something like:

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

    Is probably going to be easiest

    0 讨论(0)
  • 2020-11-21 05:43

    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

    0 讨论(0)
  • 2020-11-21 05:43

    Use this code --

    function myFunction() {
    var str = "How are you doing today?";
    var res = str.split("/");
    
    }
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题