最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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>

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>

Share Improve this question asked Dec 12, 2018 at 18:25 Mark AndersonMark Anderson 991 gold badge1 silver badge7 bronze badges 1
  • To get the content of the first num tag, try document.getElementsByTagName('num')[0].textContent – janos Commented Dec 12, 2018 at 18:27
Add a ment  | 

3 Answers 3

Reset to default 6

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.

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.

It's generally not remended 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>

发布评论

评论列表(0)

  1. 暂无评论