0

I have two links

 <a href="https://ash.confexe.com?ea=gf2014gf#safety">
    view now
 </a>
 <a href="https://ash.com?ea=gFt014gf#context1">
    view now
 </a>

I wanted to make those links make into two-slice. For example

https://ash.confexe.com?ea=gf2014gf

and

#safety

I mean I wanted to make slices before portion of # and after portion of #. I got the first portion but I am struggling with the second portion. Code is attached below.

let links = document.getElementsByTagName('a');
for(let link of links)
  {
    let curhref = link.href;
    if(curhref.indexOf('#') > -1){
  
      if(link.href.indexOf('ea=') > -1)
        {
          var z = curhref.indexOf('#');
          console.log("index no: " +z);
          //first portion
          var z1 = curhref.substring(0,z);
          console.log("First Portion: " +z1);
          
          //second portion
          var z2 = curhref.indexOf("\"",z1);
          var z2=curhref.substring(z1,0);
          console.log("second Portion: " +z2);//this should be this what i have after #
        }
    }

   
  }
<!DOCTYPE html PUBLIC>
<html>
  <body>
    <a href="https://ash.confexe.com?ea=gf2014gf#safety">view now</a><br>
    <a href="https://ash.com?ea=gFt014gf#context1">view now</a>
  </body>
</html>
Munni
  • 731
  • 5
  • 20

3 Answers3

3

A simple solution is to use .split() you can read more about it from Here

let links = document.getElementsByTagName('a');
for(let link of links)
  {
    let parts = link.href.split("#");
    console.log(parts)
   
  }
<!DOCTYPE html PUBLIC>
<html>
  <body>
    <a href="https://ash.confexe.com?ea=gf2014gf#safety">view now</a><br>
    <a href="https://ash.com?ea=gFt014gf#context1">view now</a>
  </body>
</html>
Ahmed Gaafer
  • 1,603
  • 9
  • 26
1

Follow this way. Use split method for string

let links = document.getElementsByTagName('a');
for(let link of links)
  {
    let curhref = link.href;
    if(curhref.indexOf('#') > -1){
  
      if(link.href.indexOf('ea=') > -1)
        {
          var arr = curhref.split('#')

          console.log("First Portion: " +arr[0]);
          

          console.log("second Portion: " +arr[1]);
        }
    }

   
  }
<!DOCTYPE html PUBLIC>
<html>
  <body>
    <a href="https://ash.confexe.com?ea=gf2014gf#safety">view now</a><br>
    <a href="https://ash.com?ea=gFt014gf#context1">view now</a>
  </body>
</html>
0
const links = document.getElementsByTagName('a');
const linksChunks = links.map(link => link.split('#');

Or

const links = document.getElementsByTagName('a');
links.forEach(link => {
  const chunks = link.href.split('#');
  console.log('Chunk 1: ', chunks[0]);
  console.log('Chunk 2: ', chunks[1]); 
});
Sultan Aslam
  • 5,600
  • 2
  • 38
  • 44