繁体   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