Split a pipe delimited key-value pair separated by '=' symbol

后端 未结 6 1196
醉梦人生
醉梦人生 2020-12-29 08:46

We are receiving an input parameter value as a pipe-delimited key-value pair, separated with = symbols. For example:

\"|User=0101|Name=ImNewUse         


        
相关标签:
6条回答
  • 2020-12-29 08:55

    If you do decide to use regex, make sure it's block rockin' regex like this:

    var result = {};
    
    s.replace(/([^=|]+)=([^|]*)/g, function(noStep3, a, b) { result[a] = b; });
    

    0 讨论(0)
  • 2020-12-29 09:10

    Without mutation

    You don't need the outer pipes. If necessary, trim them off str.slice(1, str.length - 1)

    const str = "User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235";
    
    str.split('|').reduce((accum, x) => { 
      const kv = x.split('=');
      return {...accum, ...{[kv[0]]: kv[1]}};
    }, {})
    
    0 讨论(0)
  • 2020-12-29 09:10

    Cleanest way possible, you can modify the source to split by a different delimiter.

    https://gist.github.com/allensarkisyan/5873977#file-parsequerystring-js

    `/**
    * @name - parseQueryString 
    * @author - Allen Sarkisyan
    * @license - Open Source MIT License
    *
    * @description - Parses a query string into an Object.
    * - Optionally can also parse location.search by invoking without an argument
    */`
    
    `
    function parseQueryString(queryString) {
        var obj = {};
        function sliceUp(x) { x.replace('?', '').split('&').forEach(splitUp); }
        function splitUp(x) { var str = x.split('='); obj[str[0]] = decodeURIComponent(str[1]); }
        try { (!queryString ? sliceUp(location.search) : sliceUp(queryString)); } catch(e) {}
       return obj;
    }
    `
    
    0 讨论(0)
  • 2020-12-29 09:13

    I would just use regular expressions to group (see here) each KEY=VALUE pair and then iterate over them to fill up the JSON object. So you could have something like this:

    var re = /(([^=\|]+)=([^=\|]+))/g;
    var match;
    var myString = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
    while (match = re.exec(myString)) {
        console.log(match);
        // first iteration returns ["User=0101","User=0101","User","0101"] and so on
    }
    
    0 讨论(0)
  • 2020-12-29 09:14
    var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
    
    
    var result = {}, name;
    str.substring(1, str.length-1).split(/\||=/).forEach(function(item, idx){
       idx%2 ? (result[name] = item) : (name = item); 
    });
    
    0 讨论(0)
  • 2020-12-29 09:16

    The first one sounds good:

    var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
    
    
    var result = {};
    str.split('|').forEach(function(x){
        var arr = x.split('=');
        arr[1] && (result[arr[0]] = arr[1]);
    });
    
    0 讨论(0)
提交回复
热议问题