Mark Anderson
Mark Anderson

Reputation: 99

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>

Upvotes: 6

Views: 11935

Answers (3)

Marie
Marie

Reputation: 2217

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.

Upvotes: 5

worc
worc

Reputation: 3786

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>

Upvotes: 1

Danny Buonocore
Danny Buonocore

Reputation: 3777

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.

Upvotes: 6

Related Questions