Javascript, create Page title with URL Query string

I am going to create the title of the page according to its URL query String

The URL sample is:

If max_price = 50000, My page title will be: Phones Under Rs.50000

If URL contains only brand like:

Page title will be: Apple phones Price list 2018

And if URL contains both price and brand like:

Page title: Apple phones under Rs.50000

here is my code:-

  function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
      vars[key] = value;
    return vars;
  var path = window.location.pathname;
  var pathName = path.substring(0, path.lastIndexOf('/') + 1);
  pathName = pathName.replace(/\//g, "")
  pathName = pathName.replace(/pricelist/g, "")

  pathName = pathName.replace(/\b\w/g, l => l.toUpperCase())

  var number = getUrlVars()["max_price"];
  var brand = getUrlVars()["brand"];
  brand = brand.replace(/\b\w/g, l => l.toUpperCase())

 if (window.location.href.indexOf("min_price") != null) {document.title = pathName + ' Under Rs. ' +  number;} 
if (window.location.href.indexOf("pa_brand") > -1) {document.title = brand + ' ' + pathName + ' Price List India';} 
if (window.location.href.indexOf("min_price") > -1 &&  window.location.href.indexOf("brand") > -1) {document.title = brand + ' ' + pathName + ' Under Rs.' + number;}


First off (in my opinion) I would try to stay away from regular expressions if I could. If you have not heard of URL Search Params, you should read up on it. It makes dealing with the query string very simple.

I also changed the capitalization to not use regular expressions too (source is this answer)

Now for the if statement, which seems like you had trouble with, try to break it down step by step.

First I see if maxPrice is not null, if its not null then great we have our first title: Phones Under Rs.${maxPrice}

Next I check if brand is not null (inside the maxPrice if) this way if brand is not null we can safely assume maxPrice is also not null, so we can change our message to ${brand} Phones Under Rs.${maxPrice}

Now since the only case where we have 2 variables in the message is done we can bounce back out of the first if and continue down to an else if. Now I check if brand is not null. If brand is not null then at this point we can assume maxPrice is also null (otherwise the code would've gone into the first if) so this gives us our final message ${brand} Phones

Now finally an else case just in case we missed something down the road, we can log it and fix the code easily.

Quick note if you are unfamiliar with the backticks in the strings they are Template Literals

var theURL = "";
var parsedURL = new URL(theURL);
// you should use instead
var searchParams = new URLSearchParams(;

var maxPrice = searchParams.get("max_price");
var minPrice = searchParams.get("min_price");
var brand = searchParams.get("brand");

// capitalize brand if it is in the query
if (brand !== null) {
  brand = brand.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

// create the title based off which query parameters come through
var title;
if (maxPrice !== null) {
  title = `Phones Under Rs.${maxPrice}`
  if (brand !== null) {
    title = `${brand} Phones Under Rs.${maxPrice}`
else if (brand !== null) {
  title = `${brand} Phones Price list 2018`
else {
  console.log(`other case came through: brand: ${brand} max_price: ${maxPrice} min_price: ${minPrice}`)


How to get current page title and add it to link directly as variable in , Am trying to create a facebook share code in just html and javascript I would I think you just want to append a "?t=" parameter to the query string which will include the page title as a query string parameter in url-encoded form. to link directly as variable in JavaScript</title> <script type='text/javascript'  JavaScript method to get the URL without query string The task is to get the URL name of the page without using a query string with the help of JavaScript. replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.

In my opinion, you're having a hard time handling if/else statements, because of overall complexity you've brought to your script. Try to make it simpler and constructing conditions will become a breeze. I have not tested it, but check out this solution:

function setTitle () {
  const search =
    .map(pair => pair.split('='))
    .reduce((acc, pair) => {
      acc[pair[0]] = pair[1];
      return acc;
    }, {});

  const brandPart = search.brand ? `${search.brand} phones` : 'Phones';
  const maxPricePart = search.max_price ? `under Rs.${search.max_price}` : '';
  const pricePart = maxPricePart || 'Price list 2018';

  document.title = `${brandPart} ${pricePart}`;

Maybe it has some problems, but it is much easier to understand and maintain.

Javascript add query parameter to url without refresh, Within IBM Cognos Report Studio, create a Query containing the use and display page title, auto refresh every x seconds (using javascript/jque To request a For example, the following URL has two query params, sort and page, with To  The multiple values to be passed to another Page will be added to the URL as QueryString parameters and then the Page will be redirected to another Page using window.location property in JavaScript. Redirecting with QueryString Parameters using JavaScript. The following HTML Markup consists of an HTML TextBox, a DropDownList and a Button.

Your code looks good and I think you can improve OR as an alternate solution, you can first create a JSON format of all query parameters. And based on JSON you can easily create the brand title.

//get query paraeters in json format
  var getParams = function (url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query =;
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    return params;
//get quer pareamaeter
var query_parameters = getParams(window.location.href);
var brand_name = '';
if ( query_parameters.max_price ) brand_name ="Phones Under Rs." + query_parameters.max_price;
if ( query_parameters.brand ) brand_name = query_parameters.brand.toUpperCase() + " phones Price list 2018"
if ( query_parameters.max_price && query_parameters.brand ) brand_name =query_parameters.brand.toUpperCase() + "phones Under Rs." + query_parameters.max_price;

Pro ASP.NET 3.5 in C# 2008, You can read or set the values in these cookies. bookmark portion of the URL string, which can point to a specific anchor on a page. QueryString Returns the query string portion of the URL as a single long string that you must parse. xmlns=""> <head> <title>Silverlight Project Test Page  JavaScript Fallback. While URLSearchParams is ideal, not all browsers support that API. There's a polyfill available but if you want a tiny function for basic query string parsing, the following is a function stolen from the A-Frame VR toolkit which parses the query string to get the key's value you'd like:

Use Query String URL in Page Title - MSDN, Is there a way of changing the page title on a page (i.e. underneath the menu, About how to get query string from URL using JavaScript, the code snippets Thanks - adding the jQuery library link seemed to do the trick. 2) Use location‘s properties. If the URL you need to parse is the URL of the page that you are currently on, then the URL is stored right inside of window.location. Better yet, location has a property called search, which will just give you the query string.

Silverlight and ASP.NET Revealed, You can read or set the values in these cookies. Cookies QueryString Returns the query string portion of the URL as a single long string that you must parse. <head> <title>Silverlight Project Test Page </title> <script type="text/javascript"  If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library. jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods. Mashups, JSON is quite easy to work with in JavaScript, as you will soon learn. Create a new file in your htdocs directory called delicious_summary.html. xml:lang=”en” lang=”en”> <head> <title>My Summary Page</title> </head> from the query string that makes up the src attribute's URL for the JavaScript include. window.location.pathname gives me the page's url without the query string. I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.

  • Could you explain exactly what the problem is? Does your code not work? How? Is an error reported? Does anything happen?
  • I cannot see a question here.
  • my code is ok but i can not handle if else statement with multiple query string if (window.location.href.indexOf("max_price") != null) {document.title = pathName + ' Under Rs. ' + number;} if (window.location.href.indexOf("brand") > -1) {document.title = brand + ' ' + pathName + ' Price List India ';} if (window.location.href.indexOf("max_price") > -1 && window.location.href.indexOf("brand") > -1) {document.title = brand + ' ' + pathName + ' Under Rs.' + number;}
  • @KavitaBirla please update your question with the comment you just posted here, to make sure the question is visible to everyone without coming to the comment section. Thanks
  • What did you change? What was the problem in the original code? How does your solution make things work? Code-only answers are not instructive.