Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove separators to urls by javascript

I have links on page and want mask them. I want, that at onLoad all points in urls (which are in href) will be replaced with something like "|",

so instead of

<a href="http://www.example.com">link</a>

there is somehting like

<a href="http://www"|"example"|"com">link</a>.

Then, at onClick replacements should be reversed to make links working again.

Need help to get this code to work:

 function mask() {
     var str = document.getElementByName("a");
     var x = str.attributes.href.value.replace('.', '"|"');
     document.getElementsByTagName("a").attributes.href.value = x;
}

function unmask(){
     var str = document.getElementByName("a");
     var x = str.attributes.href.value.replace('"|"', '.');
     document.getElementsByTagName("a").attributes.href.value = x;

}
<body onLoad="mask()">

<a href="http://www.example.com" onclick="unmask()">link</a>

</body>
like image 349
Evgeniy Avatar asked Mar 09 '26 06:03

Evgeniy


2 Answers

You have to use the getElementsByTagName method:

function mask() {
  var a = document.getElementsByTagName('a');
  for (var i = 0; i < a.length; i++) {
    a[i].attributes.href.value = a[i].attributes.href.value.replace(/\./g, '"|"');
  }
}

function unmask() {
  var a = document.getElementsByTagName('a');
  for (var i = 0; i < a.length; i++) {
    a[i].attributes.href.value = a[i].attributes.href.value.replace(/"\|"/g, '.');
  }
}
<body onLoad="mask()">
  <a href="http://www.example.com" onclick="unmask()">link</a>
</body>
like image 52
Alessio Cantarella Avatar answered Mar 10 '26 19:03

Alessio Cantarella


There are several issues in your code:

  1. document.getElementByName("a") is not valid
  2. str.attributes.href.value is not valid
  3. You need to go global replace to replace all the . with | and vice-versa.

function mask() {
     var str = document.getElementsByTagName("a")[0];
     var x = str.href.replace(/\./g, '"|"');
     str.href = x;
}

function unmask(){
     var str = document.getElementsByTagName("a")[0];
     var x = str.href.value.replace(/"|"/g, '.');
     str.href = x;
}
<body onLoad="mask()">

<a href="http://www.example.com" onclick="unmask()">link</a>

</body>
like image 28
Ankit Agarwal Avatar answered Mar 10 '26 20:03

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!