Abdullo Umarov
Abdullo Umarov

Reputation: 61

Parsing an html tag with JavaScript

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?

Upvotes: 5

Views: 2201

Answers (3)

Waqar Naeem
Waqar Naeem

Reputation: 1173

var x = "<a>1234</a>";
var tagValue = x.match(/<a>(.*?)<\/a>/i)[1];
console.log(tagValue);

it is by Regular Expression, assume x hold the value of the parsed html string:

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

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?

Upvotes: 2

Ghonima
Ghonima

Reputation: 3082

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

should work

Upvotes: 1

Related Questions