给定如下html代码,从代码中提取pathname的值和标题,返回由标题title和链接link组成的集合。
let str = `
订单管理
{ pathname: '/delete/order' }} test='1'>
删除订单
{ pathname: '/add/order' }}>
新增订单
商家管理
{ pathname: '/delete/vendoer' }} test='1'>
删除商家
{ pathname: '/add/vendoer' }}>
新增商家
`
实现
function parser(str) {
let i = 0;
let list = []
while (i < str.length) {
let space = /\s/
let char = str[i]
if (space.test(char)) {
i++;
continue
}
if (char === '<') {
let name = ''
let props = ''
let isFirst = true
i++
if (str[i] == '/') {
while (str[i] !== '>') {
i++;
}
i++;
continue
}
while (i < str.length && str[i] !== '>') {
if (space.test(str[i])) {
isFirst = false
i++
continue
}
if (isFirst) {
name += str[i++];
}
else {
while (str[i] != '>') {
props += str[i]
i++
}
}
}
i++;
let label = ''
while (i < str.length && str[i] != '<') {
if (space.test(str[i])) {
i++
continue;
}
label += str[i];
i++;
}
list.push({
name,
props,
label
})
continue
}
}
return list
}
let result = parser(str)
function transfer(list = []){
let res = []
list.forEach((item)=>{
if(item.name == 'Link'){
let title = item.label
let prop = item.props
let linkReg = /pathname:\s?'([\w\/]+)'/
let link = prop.match(linkReg)
res.push({
title,
link:link[1]
})
}
})
return res;
}
let transofrm = transfer(result)
console.log(JSON.stringify(transofrm),null,2);
结果
[
{
"title": "删除订单",
"link": "/delete/order"
},
{
"title": "新增订单",
"link": "/add/order"
}
]
[Done] exited with code=0 in 0.417 seconds
[Running] node "/Users/sundingjia/Downloads/debug-react-source-code-16.14.0/p.js"
[
{
"title": "删除订单",
"link": "/delete/order"
},
{
"title": "新增订单",
"link": "/add/order"
},
{
"title": "删除商家",
"link": "/delete/vendoer"
},
{
"title": "新增商家",
"link": "/add/vendoer"
}
]