Home > OS >  Jquery - how to get & consider only 1 URL Parameter and ignore the others?
Jquery - how to get & consider only 1 URL Parameter and ignore the others?

Time:10-24

On my shop i have a filter. When a filter is selected it adds "filter.p.tag=xxx" parameter to the url. Since i have no other possibility to display current active filters, i need to grab them from the URL. And output them under the h1 and update in realtime when a new filter is selected.

For example the URL: collections/all?filter.p.tag=animal&filter.p.tag=glitter&fbclid=2123&paramblabla=123123

-actually i only want everything after (filter.p.tag) - so in this example under the H1 Heading there should be following:

"Animal & Glitter"

I want to ignore every other parameter without "jquery remove or replace" them since this is unwanted.

THE QUESTION IS: How am i able to only consider the filter.p.tag param and ignore all others?

Now i have this code:

<script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?')   1).split('&');
    for(var i = 0; i < hashes.length; i  )
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function removeDuplicates(arr) {
        return arr.filter((item,
        index) => arr.indexOf(item) === index);
}
jQuery( document ).ready(function( $ ) {
     jQuery(document.body).on('click', ".label_filter", function(){
        setTimeout(function(){ 
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?')   1).split('&');
            for(var i = 0; i < hashes.length; i  )
            {
            hash = hashes[i].split('=');
            vars.push(hash[1]);
            // vars[hash[0]] = hash[1];
            }
            var unqvars = removeDuplicates(vars);
            var result = '';
            for(var i = 1; i <= unqvars.length; i  ){
                if(i == unqvars.length){  
                    var sept = '';
                }else{
                    var sept = ' & ';
                }               
              result = unqvars  sept;
            }
            var replaced = result.replaceAll(',', ' & ');
            var replaced1 = replaced.replaceAll(' ', '  '); 
          var replaced2 = replaced1.replaceAll('-', '  ');
          var replaced3 = replaced2.replaceAll('& Page=', ' Seite ');
    jQuery('#categoryfromfilter').text(replaced3);
        }, 1000);        
    });
});
</script>
```

CodePudding user response:

Less code, more robust

URLSearchParams().getAll() works well when there are multiple values for the same key name.

However, additional code is needed to make the function handle a wide range of input. For example, here we first parse the query string from the url. URLSearchParams would fail if the path were passed, e.g., /somepath?key=value. Query string values might also be encoded and so decodeURIComponent() is applied to each value.

const getParam = (url, key) => 
  new URLSearchParams(url?.toString().split("?").pop())
  .getAll(key).map(value => decodeURIComponent(value));

Example:

let url = "/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
    key = "filter.p.tag",
    result = getParam(url, key);

// Output: "animals,glitter"

Snippet

Code snippet that displays a range of test values.

const getParam = (url, key) => 
  new URLSearchParams(url?.toString().split("?").pop())
  .getAll(key).map(value => decodeURIComponent(value));


// Test Values

let name = "filter.p.tag";

["/collections/all?filter.p.tag=animals",
  "/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
  "/collections/all?fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
  "/collections/all?filter.p.tag=animals&fbclid=IwAR2didTPblablabla&filter.p.tag=glitter",
  "/collections/all?sort_by=apes&filter.p.tag=animals&fbclid=IwAR2didTPblablabla",
  "fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
  "filter.p.tag=animals&filter.p.tag=glitter&fbclid=IwAR2didTPblablabla",
  "/collections/all?fbclid=IwAR2didTPblablabla",
  "filter.p.tag&fbclid=IwAR2didTPblablabla",
  "/collections/all",
  null,
  undefined
].forEach(url => stdout.innerHTML  = (`Returns "${getParam(url, name)}" for  "${url}"\n`));
<xmp id="stdout"></xmp>

  • Related