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>

Sraja
  • 47
  • 3
  • What happened to the zero in the middle? – Jack Bashford Jul 31 '19 at 08:00
  • Get the text from the elements and concatenate them. Why do you want to use regex – adiga Jul 31 '19 at 08:01
  • It is a dynamic data and I am getting the value as it was described above. But this should be combined with regex. – Sraja Jul 31 '19 at 08:02
  • @adiga Because I do not know that, in how many parts this data will broken ? I gave the example that data is in 3 strong tag. Sometime it is in 2 strong tag and sometime it is in 1 strong tag. So I think regex is a good option. – Sraja Jul 31 '19 at 08:04
  • 1
    You could get `document.getElementById('data').innerText` and replace all the spaces with empty string – adiga Jul 31 '19 at 08: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](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Fix the HTML output instead of doing this shizzle. – KarelG Jul 31 '19 at 09:02

2 Answers2

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>
mlk_one
  • 36
  • 3
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.

Alex
  • 39
  • 5
  • The concat method is discouraged from Mozilla, see [this](https://stackoverflow.com/a/16124072/6707985) post and its duplicate. – geisterfurz007 Jul 31 '19 at 09:20