-1

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

The URL sample is:

domain.com/pricelist/phones/?min_price=0&max_price=50000

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

If URL contains only brand like:

domain.com/pricelist/phones/?brand=apple

Page title will be: Apple phones Price list 2018

And if URL contains both price and brand like:

domain.com/pricelist/phones/?min_price=0&max_price=50000&brand=apple

Page title: Apple phones under Rs.50000

here is my code:-

<script>
  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);
  console.log(path);
  console.log(pathName);
  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;}

</script>
  • 1
    Could you explain exactly what the problem is? Does your code not work? How? Is an error reported? Does *anything* happen? – Pointy Sep 06 '18 at 12:45
  • 1
    I cannot see a question here. – Binarus Sep 06 '18 at 12:47
  • 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;} – Kavita Birla Sep 06 '18 at 12:54
  • @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 – Armin Sep 06 '18 at 13:10

3 Answers3

0

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 = window.location.search
    .substring(1)
    .split('&')
    .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.

n1stre
  • 5,856
  • 4
  • 20
  • 41
  • 1
    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. – Pointy Sep 06 '18 at 13:08
0

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.

https://gomakethings.com/getting-all-query-string-values-from-a-url-with-vanilla-js/

//get query paraeters in json format
  var getParams = function (url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    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;
PPB
  • 2,937
  • 3
  • 17
  • 12
0

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 = "https://www.example.com?min_price=0&max_price=5000&brand=apple";
var parsedURL = new URL(theURL);
// you should use window.location.search instead
var searchParams = new URLSearchParams(parsedURL.search);

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}`)
}

  console.log(title);
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38