5

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?

3
  • maybe x.match(/\d+/) can help... Commented Mar 10, 2019 at 18:36
  • What have you tried? Also, that's not a tag, it's a string. Commented Mar 10, 2019 at 18:44
  • In general i am calculating some stuff and saving it with tag <a>. I am doing this several times but i want to add every result after calculation is done. After saving the value with <a> tag i need to get it back to add value and save it again Commented Mar 10, 2019 at 18:48

3 Answers 3

2

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?

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

Comments

1

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

should work

1 Comment

Thanks for response!
1
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:

3 Comments

Please add an explanation
it is by Regular Expression, assume x hold the value of the parsed html string:
Add that into the answer

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.