最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - split string into key value pair - Stack Overflow

programmeradmin0浏览0评论

I want to split the following string by comma if it matches key: value. Split by comma works until it encounters a comma in the value

const string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist"

I'd like to end up with this result:

[[country: Kenya],
[city: Nairobi],
[population: 3.375M],
[democracy-description: Work in progress/ Not fully met, obstacles exist]]

Thank you in advance.

I want to split the following string by comma if it matches key: value. Split by comma works until it encounters a comma in the value

const string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist"

I'd like to end up with this result:

[[country: Kenya],
[city: Nairobi],
[population: 3.375M],
[democracy-description: Work in progress/ Not fully met, obstacles exist]]

Thank you in advance.

Share Improve this question edited Sep 12, 2017 at 14:45 Nate asked Sep 12, 2017 at 13:00 NateNate 531 gold badge1 silver badge5 bronze badges 2
  • Please read What topics can I ask about and What topics to avoid and How to ask a good question and how to create a Minimal, Complete and Verifiable Example and also take the tour. We are very willing to help you fix your code, but we dont write code for you. – Serge K. Commented Sep 12, 2017 at 13:02
  • 1 I have read all that. @NathanP. – Nate Commented Sep 12, 2017 at 14:36
Add a comment  | 

3 Answers 3

Reset to default 7

You could split the string by looking if not a comma follows and a colon.

var string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist, foo: bar, bar, bar";

console.log(string.split(/, (?=[^,]+:)/).map(s => s.split(': ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Split into an array of key-value pair strings, then map that array to an array of arrays by splitting each pair:

const table =
 string.split(",") //["key:value","key:value"]
  .map(pair => pair.split(":")); //[["key","value"],["key","value"]]

To built an object out of this:

const result = Object.fromEntries(table);

//usable as:
console.log( result.country );

or use a Map:

const result = new Map(table);

//usable as:
console.log( result.get("country") );

try this one...

function getParameters() {
    var paramStr = location.search.substring(1).split("&");
    var parameters = {}
    paramStr.map(item=>{
        let keyValue = item.split('=')
        return parameters[keyValue[0]] = keyValue[1];
    })
    return parameters;
}
发布评论

评论列表(0)

  1. 暂无评论