Sraja
Sraja

Reputation: 47

Combined two HTML data value with Regex

I am trying to merege two HTML data into one HTML tag. I am trying to do it with regex.

The HTML is look like this

var temp = document.getElementById('data').innerHTML;


console.log(temp);
<div id="data">
  <strong>20 </strong>
  <strong>0 </strong>
  <strong>0 /-</strong>
</div>

My expexted output is <strong>2000/-</strong>

Upvotes: 0

Views: 54

Answers (2)

mlk_one
mlk_one

Reputation: 136

// you should get the textContent instead of the innerHTML
var temp = document.getElementById('data').textContent;

// removes all spaces and 
// surrounds the output with the <strong> element
var newhtml = `<strong>${ temp.replace(/\s/g,'') }</strong>`;

// replaces the innerHTML of the data with newhtml 
document.getElementById('data').innerHTML = newhtml
<div id="data">
  <strong>20 </strong>
  <strong>0 </strong>
  <strong>0 /-</strong>
</div>

Upvotes: 2

Alex
Alex

Reputation: 39

You do not need regex for this you could simply concat the strings with

str.concat(string2, string3, string4, etc)

and giving all the strong tags an individual ID

However, if the content is dynamic and not hard coded in, you could loop through the child nodes of document.getElementById('data') and get the textContent of each of the child nodes and concat them that way.

Upvotes: 0

Related Questions