Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 957
Mark Anderson Avatar asked Dec 12 '18 18:12

Mark Anderson


People also ask

How do I get text between tags in HTML?

The preg_match() function is the best option to extract text between HTML tags with REGEX in PHP. If you want to get content between tags, use regular expressions with preg_match() function in PHP. You can also extract the content inside element based on class name or ID using PHP.

How do I get only text from innerHTML?

In the browser that supports the standard, you can use textContent instead of innerHTML . Otherwise you can loop through the next nodes and concatenate them, or using library like jQuery that abstract this approach for you. The company is using an older version of IE and textContent returns undefined.

What is between tags in HTML?

HTML elements: Elements enclose the contents in between the tags. They consist of some kind of structure or expression. It generally consists of a start tag, content and an end tag.


1 Answers

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.

like image 63
Danny Buonocore Avatar answered Oct 02 '22 07:10

Danny Buonocore