Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Parsing string with special character and returning the output

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
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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'))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!