I want to get number that is stored in a tag likevar x="<a>1234</a>";
using JavaScript. How can I parse this tag to extract the numbers?
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).
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.
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.
Lxml. lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language.
Parse the HTML and get value from the tag.
There are 2 methods :
var x="<a>1234</a>";
var parser = new DOMParser();
var doc = parser.parseFromString(x, "text/html");
console.log(doc.querySelector('a').innerHTML)
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?
var x="<a>1234</a>".replace(/\D/g, "");
alert(x);
should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With