I have the following string:
person:juan&age:24&knowledge:html
The problem is that sometimes the string is:
knowledge:html&person:juan&age:24
And it can change the position of the keys and the values.
In this case I would write something like this:
const keys = ["person", "age", "knowledge"];
const keyAndValues = "person:juan&age:24&knowledge:html";
const result = [];
keys.forEach(key => {
  const indexKeyValues = keyAndValues.indexOf(key);
  if (indexKeyValues !== -1) {
    const lastCharIndex = keyAndValues.substring(indexKeyValues).indexOf("&");
    return keyAndValues.substring(indexKeyValues + key.length, lastCharIndex === -1 ? keyAndValues.substring(indexKeyValues).length - 1 || lastCharIndex);
  }
});
But I don't like it and it would be great if I could do something like:
const resultsExpected = /regexGroupedRegardlessOfPosition/g.match("person:juan&age:24&knowledge:html");
console.log(resultsExpected); // { person: "juan", age: 24, knowledge: "html" }
                Here is a single expression to get the object:
const keyAndValues = "person:juan&age:24&knowledge:html";
const obj = Object.assign(...keyAndValues.split('&').map(s => s.split(':'))
                                         .map(([k, v]) => ({ [k]: v }))
);
console.log(obj);
This uses ES6 destructuring assignment, spread syntax and computed property names.
You could split the string and then the parts and take the key/values for an object.
function getValues(string) {
    var object = {};
    
    string && string.split('&').forEach(p => {
        var [key, ...value] = p.split(':');
        object[key] = value.join(':');
    });
    return object;
}
console.log(getValues("knowledge:html&person:juan&age:24"));
console.log(getValues("foo:bar:baz&cool:space:aliens:survive"));
console.log(getValues(""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With