KarinaKreative
KarinaKreative

Reputation: 39

slice() returning correctly in console but string is not replaced in <td>

I am seeing the substring I expect in the console, but the original string is not being changed in the HTML.

The final result should truncate any long text in each table <td>.

Note: I do NOT want to use limitTo in the HTML on each <td> as this solution is a test for a large app utilizing thousands of tables and we don't want to manually add limits on longer content.

Here is the JS snippet I'm having issues with: (I left the comments in as they are relevant attempts to fix the problem)

 // force table content to wrap to next line after 30 characters (limit set in CSS)
        for (var i = 0; i < tableTD.length; i++){
            var text = tableTD[i].textContent;
            //var truncatedText = '';
            if(text.length > 30 ) {
                tableTD[i].classList.add('wrap');
                truncate(text, 60);
                //truncatedText = truncate(text, 60);
                //return truncatedText;

            } else { tableTD[i].classList.add('nowrap'); }

        }

        // testing
        // function truncate(str, num){
        //     var truncatedStr = '';
        //     if (str.length > num) {
        //         truncatedStr = str.slice(0, (num - 2)) + '...'
        //     }
        //     return truncatedStr;
        // };

        function truncate(str, num){
            truncateStr = str.slice(0, (num - 2)) + '...';

            return truncateStr
        }

This is what I'm seeing in the console: text truncated in console but not in HTML

Here is the full JS (angularjs 1.6.9):

var app = angular.module('myApp', []);
app.controller('karinasSandboxCtrl', function($scope)
{
    // create some lines of data
    $scope.records = [
        {
            "Name" : "Peter Rabbit",
            "Age" : "34",
            "Hobbies" : "Peter Rabbit: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".01",
            "NumberTwo" : "2828.09",
            "NumberThree" : "33829749.00",
            "NumberFour" : "379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" : "Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour" : "Four Four Four Four",
            "Notes" :"Peter Rabbit: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" :"Sailor Moon",
            "Age" :"22",
            "Hobbies" : "Sailor Moon: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Sailor Moon: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" : "Fire Lizard",
            "Age" :"987",
            "Hobbies" : "Fire Lizard: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Fire Lizard: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        }, {
            "Name" : "Tommy Turtle",
            "Age" :"24",
            "Hobbies" : "Tommy Turtle: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Tommy Turtle: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        } , {
            "Name" : "Henry Hilgard",
            "Hobbies" : "Henry Hilgard: A big long list of things that I like to do inserted here so it can be truncated. Add a few more so it goes over 90 characters and needs to be truncated.",
            "NumberOne" : ".11",
            "NumberTwo" :"28.09",
            "NumberThree" : "33829749.00",
            "NumberFour":"379234738.0922",
            "ContentToMakeLonger1" : "blah-de blah blah blah",
            "ContentToMakeLonger2" : "doop-dee-doo",
            "ContentToMakeLonger3" : "blooooop",
            "ColumnOne" : "One",
            "ColumnTwo" :"Two Two",
            "ColumnThree" : "Three Three Three",
            "ColumnFour":"Four Four Four Four",
            "Notes" :"Henry Hilgard: And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes! And a TON of notes!",
        }  
    ];

    angular.element(document).ready(function(){

        var tableTD = document.querySelectorAll('table td');

        // testing
        var str = "Testing the substring thingy here to see if it will work";
        document.getElementById("demo").textContent = truncate(str, 20);

        // force table content to wrap to next line after 30 characters (limit set in CSS)
        for (var i = 0; i < tableTD.length; i++){
            var text = tableTD[i].textContent;
            //var truncatedText = '';
            if(text.length > 30 ) {
                tableTD[i].classList.add('wrap');
                truncate(text, 60);
                //truncatedText = truncate(text, 60);
                //return truncatedText;

            } else { tableTD[i].classList.add('nowrap'); }

        }

        // testing
        // function truncate(str, num){
        //     var truncatedStr = '';
        //     if (str.length > num) {
        //         truncatedStr = str.slice(0, (num - 2)) + '...'
        //     }
        //     return truncatedStr;
        // };

        function truncate(str, num){
            truncateStr = str.slice(0, (num - 2)) + '...';

            return truncateStr
        }

    });

});

Here is the table HTML:

<table ng-controller="karinasSandboxCtrl">
    <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
          <th>Hobbies</th>
          <th>Number 1</th>
          <th>Number 2</th>
          <th>Number 3</th>
          <th>Number 4</th>
          <th>Content To Make Longer 1</th>
          <th>Content To Make Longer 2</th>
          <th>Content To Make Longer 3</th>
          <th>Column One</th>
          <th>Column Two</th>
          <th>Column Three</th>
          <th>Column Four</th>
          <th>Notes</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="x in records">
          <td>{{x.Name}}</td>
          <td>{{x.Age}}</td>
          <td>{{x.Hobbies}}</td>
          <td>{{x.NumberOne}}</td>
          <td>{{x.NumberTwo}}</td>
          <td>{{x.NumberThree}}</td>
          <td>{{x.NumberFour}}</td>
          <td>{{x.ContentToMakeLonger1}}</td>
          <td>{{x.ContentToMakeLonger2}}</td>
          <td>{{x.ContentToMakeLonger3}}</td>
          <td>{{x.ColumnOne}}</td>
          <td>{{x.ColumnTwo}}</td>
          <td>{{x.ColumnThree}}</td>
          <td>{{x.ColumnFour}}</td>
          <td>{{x.Notes }}</td>
       </tr>
   </tbody>
</table>

Here is the relevant CSS:

td {
      padding: 6px 12px;
      vertical-align: top;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 30ch; // "ch" limits number of characters per line.
      &.nowrap {
        white-space: nowrap;
      }
      &.wrap {
        white-space: normal;
        min-width: 29ch; // so the line will not wrap before 29ch
      }
    }

I'm pretty new to javascript, so I might be missing something here. I appreciate any help :)

Upvotes: 1

Views: 201

Answers (2)

zfrisch
zfrisch

Reputation: 8660

You are effectively truncating text, but you're not assigning it to your variable after it's changed.

Whenever a String is manipulated using JavaScript it does not mutate the original String, it creates a new String.

This means that when using splice you have to re-assign your initial variable. This can be done by changing

truncate(text, 60)

to

var truncatedText = truncate(text, 60)

You also need to assign the td with the new value

tableTD[i].textContent = truncatedText;

Full code

    for (var i = 0; i < tableTD.length; i++){
        var text = tableTD[i].textContent;

        if(text.length > 30 ) {
            tableTD[i].classList.add('wrap');
            var truncatedText = truncate(text, 60);
            tableTD[i].textContent = truncatedText;
            return truncatedText;

        } else { tableTD[i].classList.add('nowrap'); }

    }

    function truncate(str, num){
        truncateStr = str.slice(0, (num - 2)) + '...';

        return truncateStr;
    }

Examples:

Here is a simple Example showing that truncation works fine:

Truncated String Example

let el = document.querySelector.bind(document);

function truncate(str, num) {
  truncateStr = str.slice(0, (num - 2)) + '...';
  return truncateStr;
}


el("input").addEventListener("input", function(e) {

  const text = e.currentTarget.value,
    truncated = truncate(text, 5);

  el("output").value = truncated;

});
strong.keyword,
var.keyword {
  font-family: monospace;
  text-transform: uppercase;
  font-size: 1.2em;
}
<main>
  <input type="text" />
  <br/>
  <output name='truncated'></output>
  <br/>
  <h4>Type in the <var class="keyword">input</var> box. The <var class="keyword">output</var> will be <strong class='keyword'>truncated</strong></h4>
</main>


Here is an example of assigning String Variables to the DOM and toggling between two classes:

Assigning Truncated text to DOM

const el = document.querySelector.bind(document);
const Tbody = el("table tbody");

function truncate(str, num) {
  truncateStr = str.slice(0, (num - 2)) + '...';
  return truncateStr;
}


for (row of Tbody.rows) {
  for (cell of row.cells) {

    const text = cell.textContent,
    isLongText = text.length > 30,
    
    CL = cell.classList,
    order = isLongText ? "reverse" : "sort",
    classes = ["nowrap", "wrap"][order]();

    CL.replace(...classes) || CL.add(classes[0]);
    
    cell.textContent = isLongText ? truncate(text, 30) : text;
  }
}
td {
  padding: 6px 12px;
  vertical-align: top;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 30ch;
}

td.nowrap {
  border: inset 2px black;
  white-space: nowrap;
}

td.wrap {
  border: inset 2px red;
  white-space: normal;
  min-width: 29ch; 
}
<main>
  <table>
    <thead>
      <tr>
        <th>First Column</th>
        <th>Second Column</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>R1 - C1 This is a demonstration of truncation</td>
        <td>R1 - C2</td>
      </tr>
      <tr>
        <td>R2 - C1 This text will be truncated</td>
        <td>R2 - C2</td>
      </tr>
      <tr>
        <td>R3 - C1</td>
        <td>R3 - C2 I am not truncated!</td>
      </tr>
    </tbody>
  </table>
</main>

note: I added a colored border to see the different class assignments easier. red is wrap. black is nowrap.

Upvotes: 1

Anis R.
Anis R.

Reputation: 6912

When you pass text to truncate(text, 60), only the value of the text variable gets truncated, nothing will be applied to the HTML content itself.

Consider replacing this by:

truncate(tableTD[i].textContent, 60)

Upvotes: 0

Related Questions