0

I´m new on this and I´m having a hard time tryng to do something I think must be simple.

I have a lot of pages hosted on https://www.something.com/path/NUMBER/path/path

Inside those pages I have a button that links to https://www.example.com/path/REPLACE/path

I would like to change REPLACE on my link with NUMBER on the address bar.

This is my code:

<!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>

Thank you very much for your help!

mrkv
  • 82
  • 1
  • 14

2 Answers2

0

If you want to change using Javascript, you can do as below:

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);

-- EDIT --

Another example to replace using browser URL and replace the second path without considering the remaining URL or paths .

$(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>
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
0

try this. Url1:- 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('/');
Ravi kant
  • 89
  • 5