【问题标题】:Get the current URL of my page and add characters to it获取我页面的当前 URL 并向其中添加字符
【发布时间】:2017-05-21 18:08:22
【问题描述】:

基本上我只是希望能够获取我网页的当前 URL 并向其中添加一些字符。

例如,如果我在:localhost/index.php

我想把这个当前的 url 放在一个变量中,并在其中添加“_en”。所以它会变成:localhost/index_en.php

喜欢:var url = window.location.pathname

我尝试使用 window.location.pathname 并且可以获取 url,但我不知道如何向其中添加内容。

如果更容易的话,有没有办法在 javascript 甚至 PHP 中做到这一点? 谢谢!

【问题讨论】:

  • 不是用不同语言制作 500 个页面副本,而是使用查询字符串来提供正确的页面。

标签: javascript php url


【解决方案1】:

试试 var url = document.location.pathname; document.location.pathname = url.replace(/(\w+).(\w+)$/, '$1_en.$2');

【讨论】:

    【解决方案2】:

    您可以使用 javascript 字符串函数来修改 URL,然后将位置设置为您的新字符串。

     var oldURL = "localhost/index.php"
     var newURL = oldURL.substr(0, oldURL.indexOf(".php")) + "_en" + oldURL.substr(oldURL.indexOf(".php"), oldURL.length);
     window.location = newURL;
    

    这里是 window.location 的链接: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

    【讨论】:

      【解决方案3】:

      这可能会做到:

      var windowloc = window.location;
      var windowloc=windowloc.substr(0, indexOf("index.php")-4); // changes index.php to index
      windowloc = windowloc+"_en.php";
      

      【讨论】:

        【解决方案4】:

        要获取文档的 URL,请使用这个 document.location.href;

        现在使用替换和正则表达式 /\./ 将 URL 中的 . 替换为 _en. 以选择 . 字符。

        请注意,我要添加 _en.,因为它将替换 URL 中的旧 .

        var org_url = document.location.href;
        console.log(org_url);
        
        var new_url = org_url.replace(/\./,'_en.');
        console.log(new_url);

        【讨论】:

          【解决方案5】:

          为了修改字符串,您可以通过获取子字符串来删除最后一个.php,然后将_en.php 附加到结果子字符串中。此方法本质上等同于插入字符串 (_en)。

          如果您只想更改 URL 末尾的 *.php,这将起作用:

          var locStr = window.location;
          var newStr = locStr.substr(0, locStr.length - 4);
          newStr += "_en.php";
          

          【讨论】:

            【解决方案6】:

            在 PHP 中你可以使用:

            $cur_url = "{$_SERVER['REQUEST_URI']}";
            

            然后只需使用替换您想要的 url。如果您想将其添加到 url 的末尾,我建议您在 .php 上使用替换,因为它应该始终只出现一次。

            例如,您可以在获取 url 后添加:

            $new_url = str_replace('.php', '_en.php', $cur_url);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-06-17
              • 1970-01-01
              • 2010-11-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多