6

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>

1
  • To get the content of the first num tag, try document.getElementsByTagName('num')[0].textContent Commented Dec 12, 2018 at 18:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For additional reference for any readers: stackoverflow.com/a/1732454/2647442
5

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.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.