簡體   English   中英

獲取我的頁面的當前URL並為其添加字符

[英]Get the current URL of my page and add characters to it

基本上我只是希望能夠獲取我的網頁的當前URL並添加一些字符。

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

我想將此當前url放在變量中並為其添加“_en”。 所以它將成為:localhost / index_en.php

喜歡:var url = window.location.pathname

我嘗試使用window.location.pathname,我可以獲取網址,但我不知道如何添加內容。

有沒有辦法在javascript甚至PHP中實現它,如果它更容易? 謝謝!

嘗試var url = document.location.pathname; document.location.pathname = url.replace(/(\\ w +)。(\\ w +)$ /,'$ 1_en。$ 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

這可能會這樣做:

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

要獲取文檔的URL,請使用此document.location.href;

現在替換. 在帶有_en.的URL中_en. 使用replace和regex表達式/ /\\./進行選擇. 字符。

注意我正在添加_en. 因為它將取代舊的. 在URL中

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

為了修改字符串,可以通過獲取子字符串來刪除最后一個.php ,然后將_en.php附加到生成的子字符串中。 此方法基本上等同於插入字符串( _en )。

如果您只想更改URL末尾的*.php ,這將有效:

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

在PHP中,您可以使用:

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

然后只需使用替換你想要的網址。 如果你想將它添加到url的末尾,我建議使用.php替換,因為它應該總是只出現一次。

例如,您可以在獲取網址后添加此內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM