[英]How to get text between two custom html tags in JavaScript?
I am wondering how I can get text between two custom html tags. 我想知道如何在两个自定义html标签之间获取文本。 Example: 例:
const a = "Hello, <num>22</num>"; //And here i want to get only 22 (between these two tags <num></num> //I've tried something like this: const nr = a.match(/<num>(.*?)<\\/num>/g); console.log(nr); //But as you can see, it will only output <num>22</num>
While you could just access the contents using something like innerHTML , to answer your question from an input string via regular expression, you could use the exec() function. 虽然您可以使用innerHTML等内容访问内容,但是通过正则表达式从输入字符串中回答您的问题,您可以使用exec()函数。 This will return an array where the first element is the entire matched string <num>22</num>
, and subsequent elements will correspond to the captured groups. 这将返回一个数组,其中第一个元素是整个匹配的字符串<num>22</num>
,后续元素将对应于捕获的组。 So nr[1]
will yield 22
. 所以nr[1]
将产生22
。
const a = "Hello, <num>22</num>"; const nr = /<num>(.*?)<\\/num>/g.exec(a); console.log(nr[1]);
Note that exec()
is a function of RegExp, not String like match()
is. 请注意, exec()
是RegExp的函数,而不是像match()
那样的String。
It's generally not recommended to parse (x)html using regex . 通常不建议使用正则表达式解析(x)html 。
Just a quick snippet here that works in Chrome, it looks like you can run queries against custom tags and also use the textContent
property to get to the inner text: 这里只是一个可以在Chrome中运行的快速代码段,看起来您可以针对自定义标记运行查询,还可以使用textContent
属性来获取内部文本:
const customContent = document.querySelector('custom').textContent console.log(`custom tag's content: ${ customContent }`) const numContent = document.querySelector('num').textContent console.log(`num tag's content: ${ numContent }`)
<custom>inner text</custom> <num>some more inner text</num>
In addition to the provided answers you could also add the string to a new element and search for it normally, for example 除了提供的答案之外,您还可以将字符串添加到新元素并正常搜索它,例如
const a = "Hello, <num>22</num>"; var wrapper = document.createElement("div"); wrapper.innerHTML = a; var element = wrapper.getElementsByTagName("num")[0]; console.log(element.innerHTML);
This allows you to match without actually inserting the text into the DOM and allows you to avoid regex which is not safe when parsing html. 这允许您匹配而不实际将文本插入DOM,并允许您避免在解析html时不安全的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.