jquery新功能& JavaScript。使用jQuery替換「/」爲「:」
我
var x = location.pathname;
(例如:/abc/collection/tea/green/index.php)
喜歡我有使用location.pathname
不同的路徑檢索。
我想用「:」替換路徑名中的所有「/」(我的意思是用/ :)並且我也不想要結尾的.php文件。請任何幫助。
jquery新功能& JavaScript。使用jQuery替換「/」爲「:」
我
var x = location.pathname;
(例如:/abc/collection/tea/green/index.php)
喜歡我有使用location.pathname
不同的路徑檢索。
我想用「:」替換路徑名中的所有「/」(我的意思是用/ :)並且我也不想要結尾的.php文件。請任何幫助。
這與jQuery無關。您可以使用JavaScript來替換您的字符串。
像這樣:
var x = location.pathname;
x = x.replace(/\//g, ":");
或只是
var x = location.pathname.replace(/\//g, ":");
你也可以用同樣的方法通過將此刪除 「.PHP」:
x = x.replace(/\.php$/i, "");
(假設你只需要在最後更換一次)
基本上你必須使用str.replace()
的正則表達式版本和g
(全局)開關來完成全部替換。使用str.replace(/texthere/g, "replacement")
模式來替換多個出現 - 只記得正確逃生「texthere」這樣的字符不衝突。
如何做到這一點。完全新的javaScript。 – kishoremcp
謝謝。這是行得通的。 – kishoremcp
這應該做工精細
var x = location.pathname.replace(/\//g,':').replace(/\.php$/i,'');
它使用正則表達式。它會先用:
取代的/
所有實例,然後如果它與.php
(不區分大小寫)結束這也將被刪除(什麼也沒有替換)。
編輯:我想這個答案現在它的大部分已經分叉到對方的回答是過時的。感謝downvote,隨機的人。
我想你應該刪除的jQuery的標籤,因爲這只是一個JavaScript的問題。 –
var old_val ='/'; var new_val = old_val.replace('/',':');警報(new_val); – ImBS