请考虑以下代码:
const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"
let ids = content.match(/id='(.*?)'/g).map((val) => {
return val.replace(/id='/g,'');
})
当我console.log(ids)
时 - 我得到的结果如'x\''
,但我只需要'x'
。我想知道如何实现这一结果,我已经尝试通过随机改变正则表达式符号,因为我根本不知道正则表达式 - 似乎没有任何工作。
请不要jquery。提前谢谢
答案 0 :(得分:3)
const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"
let ids = content.match(/id='(.*?)'/g).map((val) => {
return val.replace(/id='/g,'').replace("'",'');
})
console.log(ids)
&#13;
答案 1 :(得分:2)
当你使用点“。”它意味着一切,但你正在寻找,但'人物
const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"
let ids = content.match(/id='([^' .*?])'/g).map((val) => {
return val.replace(/id='([^' .*?])'/g,'$1');
})
console.log(ids)
答案 2 :(得分:0)
这个答案解释了从一串HTML 获取DOM信息的方法,而不需要正则表达式(在解析DOM时容易出现错误和错误)。
我正在使用一个简单的库(html-fragment)从HTML字符串创建DocumentFragment。由于该字符串在内存中变为简单的DOM树,因此querySelectorAll
个元素可以id
。然后,您可以映射元素以获取ID数组。
const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>";
const fragment = HtmlFragment(content);
let ids = Array
.from(fragment.querySelectorAll('[id]'))
.map(el => el.id);
console.log(ids);
<script src="https://unpkg.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script>