如何解析键并在javascript中获取其值

时间:2018-11-07 05:21:40

标签: javascript

我正在从javascript打开URL。我需要查找术语“颜色:x”,然后检索值x。

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

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

表示网页具有字符串“ colour”。

网页看起来像这样

size: 8 colour: 1

因此,在这里,我需要检索键“颜色”的值。

1 个答案:

答案 0 :(得分:2)

要搜索任何常规文本中的模式,请执行以下操作:

如果您知道信息的书写方式,则可以使用regular expression

此正则表达式可以完成此任务:

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

(单词“ colour:”(颜色:),后跟任意空格,然后是任意数量的数字(\d+)。

捕获个数字,所以这将是我的示例中第一个捕获组(found[1])的值。

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

console.log(found[1]);

如果没有匹配项(即页面中没有'colour:xx'),则found结果将是null,因此您当然应该在之前进行检查,例如安全。

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