由于 JS 非常灵活,您可以简单地使用
data = 'link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""'
function parseData(data) {
let arrData = data.split("link:")
data = arrData.length == 2? arrData[1]: data;
let parsed_data = {}
arrData = data.split(",")
for (d of arrData){
linkInfo = /<([^>]+)>;\s+rel="([^"]+)"/ig.exec(d)
parsed_data[linkInfo[2]]=linkInfo[1]
}
return parsed_data;
}
console.log(parseData(data))
输出是
{ first: 'http://localhost:3001/posts?_page=1',
next: 'http://localhost:3001/posts?_page=2',
last: 'http://localhost:3001/posts?_page=5' }