I have the following line:
person:juan&age:24&knowledge:html
The problem is that sometimes the line:
knowledge:html&person:juan&age:24
And he can change the position of the keys and 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" }
source
share