0

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>

6
  • What happened to the zero in the middle? Commented Jul 31, 2019 at 8:00
  • Get the text from the elements and concatenate them. Why do you want to use regex Commented Jul 31, 2019 at 8:01
  • It is a dynamic data and I am getting the value as it was described above. But this should be combined with regex. Commented Jul 31, 2019 at 8:02
  • 1
    You could get document.getElementById('data').innerText and replace all the spaces with empty string Commented Jul 31, 2019 at 8:07
  • 1
    Using regex to get something done within a html string can be compared as o҉peni͏ng͏ ̷ t͘͜h͏̴̨e̷͟ ͟͞҉g̸a̧͟͟ţ̢è̵s̢̕ ͢҉ò̢f̢ ọ̘̜̻̰b̡̯̩̗͍̙ͅl̢̫̫͈͓̗̪̦̠͝i̘̗̯v̶̧̭̜̰̳͉̖̼̯͜i͚̦͘o̵̸͔̫̺͠n͔̯͙͘͠ ... read this for reference. Fix the HTML output instead of doing this shizzle. Commented Jul 31, 2019 at 9:02

2 Answers 2

2

// 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>

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

Comments

0

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.

1 Comment

The concat method is discouraged from Mozilla, see this post and its duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.