使用正则表达式从字符串中获取值

时间:2017-03-05 16:59:26

标签: javascript regex string

以下是我的字符串示例:" https://dev.testapi.com/api/v1/properties?id:xyz&surname:kronenberg&active=true"。问题是:我想保存我的字符串的最后一个值,在这种情况下它是" active:"。

字符串的另一个例子:



var url =  "https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&property_type:true";
var url =  "https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&active:true";
var url =  "https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&user_id:true";




=" https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&property_type:true"

2 个答案:

答案 0 :(得分:0)

var url1 = '"https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&property_type:true"',
    url2 = '"https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&active:true"',
    url3 = '"https://dev.testapi.com/api/v1/properties?id=xyz&surname:kronenberg&user_id:true"',
    url4 = '"dev.testapi.com/api/v1/properties?id=xyz"';

    console.log(url1.match(/(?!.+[&?])(\w+)/g)[0]);
    console.log(url2.match(/(?!.+[&?])(\w+)/g)[0]);
    console.log(url3.match(/(?!.+[&?])(\w+)/g)[0]);
    console.log(url4.match(/(?!.+[&?])(\w+)/g)[0]);

答案 1 :(得分:0)

在此处查看我的演示Regex101 Demo

(\w+)(?:(?:=|:)\w+)?$是Javascript中所需的正则表达式。

(\w+)设置capturing group

?:当在捕获组内时,表示non-capturing group

$表示声明的结尾。