簡體   English   中英

將鏈接的一部分更改為當前URL的一部分

[英]Change part of link with part of current URL

我對此很陌生,並且很難嘗試做一些我認為必須很簡單的事情。

我在https://www.something.com/path/NUMBER/path/path上托管了很多頁面

在這些頁面中,我有一個鏈接到https://www.example.com/path/REPLACE/path的按鈕

我想用地址欄上的NUMBER更改鏈接上的REPLACE。

這是我的代碼:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>

<body>

  <script>
      $(document).ready(function(){
          var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;
          pathArray = window.location.pathname.split( '/' );
          var part_2 = pathArray[2];
          var mylink = "https://www.example.com/path/" + part_2 + "/path/page.html";
      });    
  </script>

<p><a href="#" id="mylink">BUTTON</a></p>

</body>
</html>

非常感謝您的幫助!

如果要使用Java腳本進行更改,可以執行以下操作:

 var url = "https://www.something.com/path/NUMBER/path/path"; var oldUrl = "https://www.example.com/path/REPLACE/path/path"; var regex = /https:\\/\\/www\\.something\\.com\\/path\\/(\\w*?)\\/.*/g; var match = regex.exec(url); oldUrl = oldUrl.replace("/REPLACE/", "/"+match[1]+"/"); console.log(oldUrl); 

-編輯-

另一個使用瀏覽器URL替換並替換第二條路徑而不考慮其余URL或其他路徑的示例。

 $(document).ready(function() { var url = window.location.href; // As the script executed in iframe, assigning with hardcode value url = "https://stackoverflow.com/questions/51442637/change-part-of-link-with-part-of-current-url#"; var oldUrl = "https://www.example.com/path/REPLACE/path/path"; var regex = /https:\\/\\/\\w*?\\.?\\w*?\\.\\w*?\\/\\w*?\\/(\\w*?)\\/.*/g; var match = regex.exec(url); oldUrl = oldUrl.replace("/REPLACE/", "/" + match[1] + "/"); document.getElementById("mylink").href = oldUrl; }); 
 <!doctype html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> </head> <body> <p><a href="https://stackoverflow.com/questions/51442637/change-part-of-link-with-part-of-current-url#" id="mylink">BUTTON</a></p> </body> </html> 

嘗試這個。 網址1 :-https://www.something.com/path/NUMBER/path/path; URL2: - https://www.example.com/path/REPLACE/path ;

url2 = url2.split('/').map(a => {
    if(a == 'REPLACE') 
        return 'NUMBER'; 
    else 
        return a;
}).join('/');

暫無
暫無

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

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