Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing an html tag with JavaScript

Tags:

I want to get number that is stored in a tag like
var x="<a>1234</a>"; using JavaScript. How can I parse this tag to extract the numbers?

like image 842
Abdullo Umarov Avatar asked Mar 10 '19 18:03

Abdullo Umarov


People also ask

What is parseHTML in JavaScript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How do you parse an element in HTML?

If you just want to parse HTML and your HTML is intended for the body of your document, you could do the following : (1) var div=document. createElement("DIV"); (2) div. innerHTML = markup; (3) result = div. childNodes; --- This gives you a collection of childnodes and should work not just in IE8 but even in IE6-7.

What is HTML parsing?

HTML parsing involves tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.

Which library can be used to parse HTML & XML?

Lxml. lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language.


2 Answers

Parse the HTML and get value from the tag.

There are 2 methods :

  1. Using DOMParser :

var x="<a>1234</a>";

var parser = new DOMParser();
var doc = parser.parseFromString(x, "text/html");

console.log(doc.querySelector('a').innerHTML)
  1. Creating a dummy element

var x = "<a>1234</a>";
// create a dummy element and set content
var div = document.createElement('div');
div.innerHTML = x;

console.log(div.querySelector('a').innerHTML)

Or using regex(not prefered but in simple html you can use) :

var x = "<a>1234</a>";

console.log(x.match(/<a>(.*)<\/a>/)[1])

console.log(x.match(/\d+/)[0])

REF : Using regular expressions to parse HTML: why not?

like image 168
Pranav C Balan Avatar answered Oct 11 '22 22:10

Pranav C Balan


var x="<a>1234</a>".replace(/\D/g, "");
alert(x);

should work

like image 45
Ghonima Avatar answered Oct 12 '22 00:10

Ghonima