I would like to split the below value:
var stringValue = "<a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a><a href="/EN/Company/OurOrganisation/ActionsEN.pdf">EN</a><a href="/FR/Company/OurOrganisation/ActionsFR.pdf">FR</a>";
As we see, there are 3 anchors hence I have tried
1. var result = stringValue.split("<a/>");
2. var myRegexp = new RegExp("<a/>");
var result = stringValue.split(myRegexp);
What would be the best regex or way to get these 3 anchors ?
答案 0 :(得分:4)
这是一个纯正的正则表达式解决方案:
var stringValue = '<a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a><a href="/EN/Company/OurOrganisation/ActionsEN.pdf">EN</a><a href="/FR/Company/OurOrganisation/ActionsFR.pdf">FR</a>';
var ar = stringValue.match(/<a.*?<\/a>/g)
console.log(ar)
&#13;
答案 1 :(得分:1)
您可以使用正向预测断言来获得分割位置
var stringValue = '<a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a><a href="/EN/Company/OurOrganisation/ActionsEN.pdf">EN</a><a href="/FR/Company/OurOrganisation/ActionsFR.pdf">FR</a>';
var res = stringValue.split(/(?=<a.*?<\/a>)/);
console.log(res);
<强> Regex explanation 强>
答案 2 :(得分:0)
你已经在那里,只需要一个额外的步骤(好吧,可能是2)
var finalArray = stringValue.split("</a>").filter( function(val){
return val.length > 0; //filter out empty results
}).map( function(val){
return val + "</a>"; //append "</a>" to the rest of the results
})
答案 3 :(得分:0)
首先,您的字符串包含双引号("
),您应该将它们转义或将其封装在单引号('
)中。
var stringValue = '<a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a><a href="/EN/Company/OurOrganisation/ActionsEN.pdf">EN</a><a href="/FR/Company/OurOrganisation/ActionsFR.pdf">FR</a>';
var result = stringValue.split("</a>")
.filter(function(item) {
return item ? true : false;
})
.map(function(item) {
return item + '</a>';
});