Tamilmani Natarajan
Tamilmani Natarajan

Reputation: 23

How to parse the key and get its value in javascript

I am opening a URL from javascript. I need to look for the term "colour: x" and then retrieve the value x.

request.get("URL", function (error, res, body)

val = body.indexOf('colour') -> works

which means that web page has the string "colour".

Web page looks like this

size: 8 colour: 1

So, Here I need to retrieve the value of the key 'colour'.

Upvotes: 1

Views: 80

Answers (1)

Pac0
Pac0

Reputation: 23174

To search for a pattern in any general text:

You can use a regular expression if you know how your information is written.

This regular expression should do the job :

/\bcolour:\s+(\d+)/

(the word "colour:" followed by any space, and then by any number of digits (\d+).

It captures the digits, so this will be the value of the first capture group (found[1]) in my example.

body = `size: 8 colour: 1`
    
let regex = /\bcolour:\s+(\d+)/;
let found = body.match(regex);

console.log(found[1]);

In the case there is no match (i.e., no 'colour: xx' in the page), the found result will be null, so you should of course check for it before, for safety.

    body = `size: 8 but unfortunately, no colour here`
        
    let regex = /\bcolour:\s+(\d+)/;
    let found = body.match(regex);

    //console.log(found[1]); // Uncaught TypeError: Cannot read property '1' of null
    
    // This snippet below is safe to use :
    if (found) {
       console.log(found[1]);
    } else {
       console.log('not found');
    }

Upvotes: 2

Related Questions