Replace symbol with tag using jquery
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
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>');
});
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 );
});
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.
精彩评论