正则表达式查找标签 ID 和内容 JavaScript
嘿,我正在尝试用 javascript 中的正则表达式做一些非常具体的事情,而我的 regexp-foo 充其量是不稳定的。想知道是否有专业人士可以为我指出正确的方向。所以我有一些文本...
<item id="myid1">myitem1</item>
<item id="myid2">myitem2</item>
...等等
我想将其剥离到一个数组中读取 myid1, myitem1, myid2, myitem2, ....etc
永远不会有嵌套元素,因此不存在递归嵌套问题。有谁能快速解决这个问题吗? 感谢您的帮助!
Hey I'm trying to do something quite specific with regex in javascript and my regexp-foo is shakey at best. Wondered if there were any pros out there who could point me in the right direction. So I have some text...
<item id="myid1">myitem1</item>
<item id="myid2">myitem2</item>
...etc
And I would like to strip it out into an array that reads
myid1, myitem1, myid2, myitem2, ....etc
There will never be nested elements so there is no recursive nesting problem. Anyone able to bash this out quickly?
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个正则表达式,它将:
注意:
我懒得在这里匹配属性值。它需要用双引号括起来,并且属性名称与其值之间不需要有空格。
在 javascript 中运行正则表达式将如下完成:
最后,
results
将是一个如下所示的对象:YMMV if the- ;元素包含嵌套的 HTML。
Here's a regex that will:
Note:
I am being lazy in matching the attribute value here. It needs to be enclosed in double quotes, and there needs to be no spaces between the attribute name and its value.
Running the regex in javascript would be done like so:
At the end of this,
results
would be an object that looks like:YMMV if the <item> elements contain nested HTML.
如果有人真的喜欢或需要使用正则表达式通过 id 获取 HTML 标签(如问题主题中的),他可以使用我的代码:
我还制作了一个通过类名获取元素的代码:
If someone really like or need to use Regex to get an HTML tag by id (like the in the question subject), he can use my code:
I made also one to get element by class name:
我总是使用这个网站来构建我的正则表达式:
http://www.pagecolumn.com/tool/ regtest.htm
这是我想出的正则表达式:
这是页面为我提供的 JavaScript 结果
使用 RegExp 对象:
使用文字:
I always use this site to build my regexes:
http://www.pagecolumn.com/tool/regtest.htm
This is the regex I came up with:
And this is the result that the page gives me for JavaScript
Using RegExp object:
Using literal:
这是一个 xml 字符串。在我看来,XML 解析器似乎最适合此类任务。执行以下操作:
如果您的问题是无法将 xml 字符串转换为 xml 对象,则必须事先使用 DOM 解析器:
然后使用上面的脚本。
This is a xml string. A XML parser seems suited best for this kind of task in my opinion. Do the following:
If your problem is that you cannot convert the xml string to an xml object, you will have to use a DOM parser beforehand:
Then use the above script.