如何使用JS切片链接



我有两个链接

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

我想把这些链接分成两片。例如

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

#safety

我的意思是我想在#部分之前和#部分之后制作切片.我得到了第一部分 但我正在为第二部分而苦苦挣扎。代码附在下面。

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>

一个简单的解决方案是使用 .split(( 你可以从这里阅读更多关于它的信息

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>

按照这个方式。对字符串使用拆分方法

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>

const links = document.getElementsByTagName('a');
const linksChunks = links.map(link => link.split('#');

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

最新更新