I know its a pretty simple question, but to anyone who is new to Javascript this can be interesting.
Is there any fastest way to parse this string and get the color for the fruit like shown below :
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
var applecolor = getColor("APPLE") // RED
var bananaColor = getColor("BANANA") //yellow
Here is a regex match approach:
function getColor(fruitAndColors, fruit) {
return fruitAndColors.match(new RegExp("\\b" + fruit + "=([^&]+)"))[1];
}
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
console.log(getColor(fruitAndColors, "APPLE")); // RED
console.log(getColor(fruitAndColors, "BANANA")); //yellow
For the case of searching for APPLE we use the following regex pattern:
\bAPPLE=([^&]+)
This places the key (the color) in the first capture group, which the helper function then returns.
Regex will probably be the best bet for this however it is definitely not my strong-suit. That said, here's what I came up with just some Javascript:
var fruitAndColors =
'APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange';
const getColor = (key) => {
const entries = fruitAndColors.split('&').reduce((acc, val) => {
const [fruit, color] = val.split('=');
acc[fruit] = color;
return acc;
}, {});
return entries[key];
};
var appleColor = getColor('APPLE'); // RED
var bananaColor = getColor('BANANA'); //yellow
A little class that handle that kind of url parse
class UrlParse {
#objects;
constructor(uri) {
this.uri = uri
this.objects = {}
this.parse()
}
parse() {
let arr = this.uri.split('&')
for (let a of arr) {
let arr = a.split(/\=/)
this.objects[arr[0]] = arr[1]
}
}
getName(name) {
return this.objects[name]
}
}
var fruitAndColors = "APPLE=RED&GUAVA=GREEN&STRAWBERRY=RED&BANANA=yellow&ORANGE=orange"
let p = new UrlParse(fruitAndColors)
console.log(p.getName('BANANA'))