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
.