Truncate string on toggle in JS

I have this container which should change the color on toggle, and the strings inside it should be checked for the length. If the string is longer than 20 characters, trucate it and add "..." at the end. If it’s shorter, leave it as it is. For some reason the slice does not work correctly in my case, it seems to cut more characters than it is set… Also, I can’t seem to get the innerHTML to insert the new trucated string in place. I’m writing it in ES6 syntax, can’t get it working in the fiddle – sorry about that. Any help appreciated.

constructor() {
  this.container = document.querySelector(".blue-bg");
  this.string = document.querySelector(".string").innerHTML;
  this.toggle = document.querySelector(".toggle");
events() {
  this.toggle.addEventListener("click", () => this.toggleMe());

truncateString(str, num) {
  if (str.length <= num) {
    return str
  return str.slice(0, num) + '...'

toggleMe() {

  if (container.classList.contains("blue-bg") && string.length >= 20) {
    this.string = this.truncateString(this.string, 20);
  } else {
    //just return string

18 thoughts on “Truncate string on toggle in JS”

Leave a Comment