简体   繁体   English

Javascript,使用 URL 查询字符串创建页面标题

[英]Javascript, create Page title with URL Query string

I am going to create the title of the page according to its URL query String我将根据其 URL 查询字符串创建页面的标题

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如果 max_price = 50000,我的页面标题将是:Phones Under Rs.50000

If URL contains only brand like:如果 URL 仅包含如下品牌:

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

Page title will be: Apple phones Price list 2018页面标题将是:苹果手机价格表 2018

And if URL contains both price and brand like:如果 URL 包含价格和品牌,例如:

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

Page title: Apple phones under Rs.50000页面标题: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>

In my opinion, you're having a hard time handling if/else statements, because of overall complexity you've brought to your script.在我看来,您很难处理if/else语句,因为您给脚本带来了整体复杂性。 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.也许它有一些问题,但它更容易理解和维护。

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.您的代码看起来不错,我认为您可以改进 OR 作为替代解决方案,您可以先创建所有查询参数的 JSON 格式。 And based on JSON you can easily create the brand title.基于 JSON,您可以轻松创建品牌名称。

https://gomakethings.com/getting-all-query-string-values-from-a-url-with-vanilla-js/ 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;

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.如果您还没有听说过URL Search Params ,那么您应该仔细阅读它。 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.现在对于似乎您遇到问题的if语句,请尝试逐步分解它。

First I see if maxPrice is not null, if its not null then great we have our first title: Phones Under Rs.${maxPrice}首先,我查看 maxPrice 是否不为 null,如果不为 null,那么很好,我们有了我们的第一个标题: 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}接下来我检查brand是否不为空(在maxPrice if )如果brand不为null我们可以安全地假设maxPrice也不为null ,因此我们可以将消息更改为${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 .现在,由于我们在消息中有 2 个变量的唯一情况已经完成,我们可以从第一个if中弹回并继续下降到else if Now I check if brand is not null .现在我检查brand是否不为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如果brand不为null那么此时我们可以假设maxPrice也是null (否则代码将进入第一个if )所以这给了我们最后的消息${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.现在终于有一个else案例,以防万一我们错过了一些东西,我们可以记录它并轻松修复代码。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM