将链接的一部分更改为当前URL的一部分

时间:2018-07-20 12:32:31

标签: javascript jquery html url href

对此我是新手,我很难尝试做一些我认为必须很简单的事情。

我在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>

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果要使用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 :(得分:0)

尝试一下。     网址1:-https://www.something.com/path/NUMBER/path/path;     网址2:-https://www.example.com/path/REPLACE/path;

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