0

I have specification for products in text doc that I need to transfer into HTML.

Might sound a bit strange but but what I'm trying to do is replace paragraph tags into two table columns, so this:

<p>Load (kg):5,000, 10,000, 20,000, 30,000</p>
<p>Excitation  Voltage: 10vdc recommended, 20vdc maximum</p>

into this

 <tr>
    <td>Load (kg)</td>
    <td>5,000, 10,000, 20,000, 30,000</td>
  </tr>

 <tr>
    <td>Excitation  Voltage</td>
    <td>10vdc recommended, 20vdc maximum</td>
  </tr>

To replace paragraph tag I've used function bellow

$("p").each(function () {
      $(this).replaceWith("<td>" + $(this).text() + '</td>');
    });

So I have to hook up to ' : ' to close and close and open another table data (column)

Any help much appreciated

Thank you in advance

Dom

3 Answers 3

2

This is specific to your particular example and assumes well-conditioned data. If you can have multiple colons in the text, you'll need to adjust use the limit argument of split to limit it to 2 results.

$("p").each(function () {
  var text = $(this).text().split(':');
  $(this).replaceWith("<td>" + text[0] + '</td><td>' + text[1] + '</td>');
});
1

You can use split and get the index 0 value to be placed in the first td and index 1 value placed in the second td.

Something like this

$("p").each ( function() {
    var splitArr = $(this).text().split(':');
    var str = "<table><tr><td>";
    str+= splitArr[0] + "</td><td>";
    str += splitArr[1] + "</td>";
    str += "</tr></table>";

    $(this).replaceWith ( str );
});
1

The easiest way is probably to use regExp:

$('p').each(function() {
    $(this).replaceWith("<tr><td>"+$(this).text().replace(/\:\s?/, '</td><td>')+'</td></tr>');
})

Also supports multiple cells and stripping white-space after the colon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.