Context: I have a script for a search page that retrieves the value for the selected filter from the URL and appends the text " in 'filter'." to the h1 heading on the search results page.
For example, if you search for ‘sql’ and apply the ‘Installation guide’ filter, the URL will show .../Search.htm?q=sql&f=Installation%20Guide and the search results page will say:
Your search for "sql" returned 9 results in Installation Guide.
However, if no filter is selected, there is no 'f=' and a blank is appended. In that case, the search results page will say:
Your search for "sql" returned 9 results in .
Here's the script:
$(document).ready(function(){
var filter=(window.location.search.split('&').splice(1)) //Creates a "filter" variable whose value is the filter text.
filter = decodeURI(filter) //Removes the codes used for spaces.
filter = filter.substring(2) //Removes "f=" at the beginning.
var $span = $( document.createElement('span') ); //Creates a span element to contain the new text.
$span.addClass('filter'); //Adds the class filter to the span in case you would need to edit the styling.
$span.text(" in "+'' + filter +'' + ".") //Inserts text and the value from the URL.
$("h1").append($span) //Appends the new span to the existing string.
});
Question: How can I modify the script to only report the filter if it's selected (if 'f=' exists)?
Thanks in advance!
You can simply use URL API to parse url instead of writing a custom logic for it. URL.searchParams will parse all the query filters in the url and provide a proper api to get them. See the code below
$(document).ready(function() {
const url = new URL(window.location.href);
var filter = url.searchParams.get("f");
if (filter) {
var $span = $(document.createElement('span')); //Creates a span element to contain the new text.
$span.addClass('filter'); //Adds the class filter to the span in case you would need to edit the styling.
$span.text(" in " + '' + filter + '' + ".") //Inserts text and the value from the URL.
$("h1").append($span) //Appends the new span to the existing string.
}
});