Home > Enterprise >  Find string and replace with HTML
Find string and replace with HTML

Time:04-22

There is a table with a column which I want to separate in two. The cell's content of this column is e. g.

| Miami: banana         |
| Ft. Myers: pineapple  |

Now I want to split this into two columns (and cells) to appear like this:

| Miami      | banana      |   // <td> Miami </td><td> banana </td>
| Ft. Myers  | pineapple   |   // <td> Ft. Myers </td><td> pineapple </td>

I made a JavaScript to achieve this:

function foo(str) {
  result = str.replace(": ", "</td><td>");
}

$("td.valueCol").each(function(){
  $("td.valueCol").html(foo($(this).text()));
}

The result however is:

| bananas      |     // <td>bananas</td>
| pineapple    |     // <td>pineapple</td>

When I test it with a not parsed tag like result = str.replace(": ", "</xt><xt>") it shows, that the tags are swapped and quotation marks are added to the part before the tag:

| Miamibarbananas          |     // <td>"Miamibar"<xt>bananas</xt></td>
| Ft. Myersbarpineapple    |

Obviously replace or html() applies some sort of sanitizing. What is this, and what do I have to do to make it work properly?

CodePudding user response:

I just played around a little bit with some Vanilla JavaScript and it turns out that .outerHTML might "be your friend" here:

document.querySelectorAll("td")
 .forEach(td=>td.outerHTML=td.outerHTML.replace(":","</td><td>"))
TD {border: 1px solid grey}
<table>
<tr><td>a:b</td><td>v:d</td><td>ef</td></tr>
<tr><td>f:h</td><td>i:j</td><td>kl</td></tr>
<tr><td>m:n</td><td>o:p</td><td>rs</td></tr>
</table>

CodePudding user response:

You can use jQuery's insertAfter() to create a new TD next to the one you're splitting.

$('table td').each(function() {
  let v = $(this).text().split(':');
  if (v.length > 1) {
    $(this).text(v[0]);
    $(`<td>${v[1]}</td>`).insertAfter($(this))
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border='1'>
  <tr>
    <td>Miami: banana</td>
    <td>Ft. Myers: pineapple</td>
  </tr>
</table>

CodePudding user response:

firstly i wanted to say when you are selecting all td elements and nesting them with more td inside them which is invalid html although browser will sort this out so what i came up with is selecting all row and create new td's in one level by splitted array in below manner

$("tr").each(function(){
// iterate once per row
    let values = $(this).text().split(":"),
        newMarkup = ""
    values.forEach(function(each){newMarkup  = "<td>"   each.trim()   "</td>"})
    $(this).html(newMarkup)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
  tr,td {
    border:1px solid black;
    padding:2px;
  }
  td {padding:5px;}
</style>

<table>
    <tbody>
        <tr><td>Miami: banana</td></tr>
        <tr><td>Ft. Myers: pineapple</td></tr>
    </tbody>
</table>

  • Related