简体   繁体   English

如何从javascript中的字符串中提取参数(指定的模式字符串)

[英]how to extract parameter(specified pattern string) from string in javascript

I need to extract parameter name from the url path. 我需要从网址路径中提取参数名称。 parameters are inside {} or follow the first ?(questionmark) or follow & mark in the url. 参数位于{}内,或跟随第一个?(问号)或跟随url中的&标记。

the url path need to be extracted is in such format : 需要提取的url路径是这样的格式:

/tt/{pa}/{pb}/?p1=9888&p2=9&p3=98

thus the parameters are pa , pb , p1 , p1 , p3 因此参数是papbp1p1p3

Quickest way I can think of is this: 我能想到的最快方法是:

[{?&][^}=]+

正则表达式可视化

Debuggex Demo Debuggex演示

Now I'm also capturing the { or ? 现在,我还在捕获{? or & character preceding it, so you'd have to cut that off afterwards: &之前的字符,因此您之后必须将其删除:

 var inp = '/tt/{pa}/{pb}/?p1=9888&p2=9&p3=98' var found = inp.match(/[{?&][^}=]+/g).map(function(p){ return p.substring(1); }); document.write(found.join('<br />')); 

And if you expect something like /tt/{pa=}/{pb}/?p1={9888&p2=9&p3=98 where pa= is a valid param name and/or {9888 is a valid value, you'd be in trouble. 而且,如果您希望输入类似/tt/{pa=}/{pb}/?p1={9888&p2=9&p3=98 ,其中pa=是有效的参数名称和/或{9888是有效的值,麻烦。 But I doubt this is a serious limitation. 但是我怀疑这是一个严重的限制。

Simple example for extracting separately search variables and variables from path: 从路径中分别提取搜索变量和变量的简单示例:

function extractSearch(search) {
    var result = {};

    search = search || window.location.search;

    if (search.length) {
        search = search.substr(1).split('&');

        for (var i = 0; i < search.length; i++) {
            search[i] = search[i].split('=');
            result[decodeURIComponent(search[i][0])] = decodeURIComponent(search[i][1]);
        }
    }

    return result;
}

function extractFromPath(pattern, url) {
    var keys = [],
        result = {},
        i;

    url = url || window.location.pathname;

    pattern = pattern.replace(/{([^}]+)}/g, function($0, $1) {
        keys.push($1);
        return '([^/]+)';
    });

    pattern = url.match(new RegExp('^' + pattern));

    for (i = 0; i < keys.length; i++) {
        result[keys[i]] = pattern[i + 1];
    }

    return result;
}

Example of use: 使用示例:

// Object {a: "10", b: "20"}
extractSearch('?a=10&b=20');

// Object {pa: "1", pb: "2"}
extractFromPath('/tt/{pa}/{pb}', '/tt/1/2/?p1=9888&p2=9&p3=98');

Eventually you can combine it by: 最终,您可以通过以下方式将其组合:

function getParameters(pattern, path) {
    var result,
        tmp;

    path = path.split('?');

    result = extractFromPath(pattern, path[0]);

    if (path[1] !== void 0) {
        tmp = extractSearch('?' + path[1]);

        for (var param in tmp) {
            result[param] = tmp[param];
        }
    }

    return result;
}

// Object {pa: "1", pb: "2", a: "10", b: "20"}
getParameters('/tt/{pa}/{pb}', '/tt/1/2?a=10&b=20');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM