假设我有一个从 HTML 代码中提取的字符串。
<div>
<foreignobject height="70" width="70" x="152" y="20"><input data-accept="1" /></foreignobject>
<foreignobject height="70" width="70" x="305" y="20"><input data-accept="2" /></foreignobject>
</div>
我想做的是将它们转换成类似的东西
<div>
<span style="position: absolute; left: 152px; right: 20px"><input data-accept="1" /></span>
<span style="position: absolute; left: 305px; right: 20px"><input data-accept="2" /></span>
</div>
我的策略是
- 获取
<foreignobject
之间的所有字符串和/></foreignobject>
,我现在还在挣扎。我的想法是使用
var open = '<foreignobject', close = '/></foreignobject>';
var rege = new RegExp(open +'(.*?)' + close)
var arrBetween = st.split(rege);
显示arrBetween
一个数组,其元素 1 和 3 是我需要的
0: "<div> "
1: " height="70" width="70" x="152" y="20"><input data-accept="1" "
2: " "
3: " height="70" width="70" x="305" y="20"><input data-accept="2" "
4: "</div>"
我该如何获取arrBetween
我只需要元素,在本例中是 2 个元素?
最佳答案
使用 DOMParser 来提取属性怎么样?
const input = `<div>
<foreignobject height="70" width="70" x="152" y="20"><input data-accept="1" /></foreignobject>
<foreignobject height="70" width="70" x="305" y="20"><input data-accept="2" /></foreignobject>
</div>`;
const doc = new DOMParser().parseFromString(input, 'text/html');
doc.body.querySelectorAll('foreignobject').forEach((foreignobject) => {
const span = document.createElement('span');
const x = foreignobject.getAttribute('x');
const y = foreignobject.getAttribute('y');
span.style = `position: absolute; left: ${x}px; right: ${y}px`;
span.innerHTML = foreignobject.innerHTML;
foreignobject.replaceWith(span);
});
console.log(doc.body.innerHTML);
如果可能的话,best to avoid使用正则表达式来解析 HTML。
关于javascript - 获取多个字符串之间的字符串,即 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59135338/