简体   繁体   中英

How to get text between two custom html tags in JavaScript?

I am wondering how I can get text between two custom html tags. 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. 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. So nr[1] will yield 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.

It's generally not recommended to parse (x)html using regex .

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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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