How to get empty href request parameters?

I need a function to get only empty href request parameter names, so I can replace them later with values ​​from another array. After several hours of failure with regular expressions, I turned to:

/**
* getEmptyQueryParams(URL)
* Input: URL with href params
* Returns an array containing all empty href query parameters.
*/
function getEmptyQueryParams(URL)
{

    var params = new Array( );
    var non_empty_params = new Array( );
    var regex = /[\?&]([^=]+)=/g; // gets all query params
    var regex2 = /[\?&]([a-zA-Z_]+)=[\w]/g; // gets non empty query params 

    while( ( results = regex.exec( URL ) ) != null )
    {
        params.push( results[1] );
    }
    while( ( results = regex2.exec( URL ) ) != null )
    {
        non_empty_params.push( results[1] );
    }
    while(non_empty_params.length > 0)
    {
        for(y=0;y < params.length;y++)
        {
            if(params[y] == non_empty_params[0])
            {
                params.splice(y,1);
            }
        }
        non_empty_params.shift();
    }
    return params;
}

It works, but it looks ugly, like hell ... Is there a better way to do this? Any help is appreciated.

+3
source share
4 answers

I just checked that this works in Opera and Chrom, the two browsers I was opening right now:

function getEmptyQueryParams(URL)
{
    var params = new Array();
    var regex = /[\?&]([^=]+)=(?=$|&)/g; // gets non empty query params
    while( ( results = regex.exec( URL ) ) != null )
    {
        params.push( results[1] );
    }

    return params;
}
+4
source

I think you could do this with one regex that matches empty and populated parameters.

var regex = /[\?&]([a-zA-Z_]+)=([\w]*)/g;

while( ( results = regex.exec( URL ) ) != null )
{
    if (results[2] == '')
        params.push( results[1] );
}

Of course, you need to test.

0
$parsedUrl = parse_url($url);
$query = $parsedUrl['query'];
$params = array();
parse_str($query, $params);

$emptyParamNames = array();
foreach ($params as $k=>$v) {
    if ($ v === "")
        $ emptyParamNames [] = $ k;
}

EDIT:

Heh ... thought for some reason this flagged PHP.

Well, maybe someday this will be useful to someone :)

0
source
function get_url_params($url) {
    $out = array();
    $parse = parse_url($url, PHP_URL_QUERY);
    if($parse) {
        foreach(explode('&', $parse) as $param) {
            $elems = explode('=', $param, 2);
            $out[$elems[0]] = $elems[1];
        }
    }
    return $out;
}

function get_empty_url_params($url) {
    $out = array();
    foreach(get_url_params($url) as $key => $value)
        if(empty($value))
            $out[] = $key;
    return $out;
}
0
source

Source: https://habr.com/ru/post/1706076/


All Articles