简体   繁体   English

Javascript正则表达式-从字符串html获取div ID

[英]Javascript Regex - get div IDs from string html

Consider the following code: 考虑以下代码:

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,'');
})

And when I do console.log(ids) - I get the output like this 'x\\'' but I need only 'x' . 当我做console.log(ids) ,我得到的输出是这样的'x\\''但我只需要'x' I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working. 我想知道如何获得该结果,我尝试通过随机更改正则表达式符号进行尝试,因为我根本不了解正则表达式-而且似乎没有任何作用。

No jquery please. 请不要使用jQuery。 Thank you in advance 先感谢您

 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) 

when you use dot "." 当您使用点“。” it means everything but you are searching everithing but ' character 这意味着一切,但你正在搜寻一切,但“性格”

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)

This answer explains an approach to getting DOM information from a string of HTML without the need for Regular Expressions (prone to bugs and errors when parsing DOM). 此答案说明了一种从HTML字符串获取DOM信息而无需正则表达式的方法 (解析DOM时容易出现错误和错误)。

I am using a simple library (html-fragment) to create a DocumentFragment from the string of HTML. 我正在使用一个简单的库(html片段)从HTML字符串创建DocumentFragment。 Since that string becomes a simple DOM tree in memory, you can querySelectorAll elements with the id attribute. 由于该字符串成为内存中的简单DOM树,因此可以使用具有id属性的querySelectorAll元素。 You can then map the elements to get the array of ids. 然后,您可以映射元素以获取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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM