skip to Main Content

I’m trying to optimize my titles for Google SEO (title tag in html).

I have product titles that are 3-4 lines long and just look like garbage. I would like to basically find the last full word before the 65 character in a sring.

So if ‘foo bar baz buzz’ were the middle of a long string and the “a” in “baz” were the 65th character I’d want to just exclude “baz” and everything after it.

3

Answers


  1. Chosen as BEST ANSWER

    This is what I ended up going with:

    function truncateTitle(str, len = 60) {
      //get a temporal substring with the desired length
      if (str.length <= len) {
        return str;
      }
    
      const temp = str.substr(0, len);
    
      //get the last space index
      const lastSpaceIdx = temp.lastIndexOf(' ');
    
      //get the final substring
      return temp.substr(0, lastSpaceIdx).trim();
    }
    

  2. You should check that the string is longer than the desired length and if it is…

    var title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In id diam vitae enim maximus consequat sit amet eu elit. Sed.";
    
    const substr_length = 65;
    
    //get a temporal substring with the desired length
    var temp = title.substr(0, substr_length);
    
    //get the last space index
    var ls_index = temp.lastIndexOf(" ");
    
    //get the final substring
    var short_title = temp.substr(0, ls_index).trim();
    
    //done
    
    Login or Signup to reply.
  3. Hmmm! I like the other solutions, but I want to give it my own shot.

    What I realized is that if the last word is complete, there MUST be a space after it.

    So all you need to do is increment your desired length by +1. If the 66th character is a space, then the last word before it is complete and you don’t need to discard it. If it isn’t, then discard.

    If the last char is a space, whenever you .split() at the spaces it will create an empty string as a last element, since it interprets the last space as a splitting point – so you can .pop() the last element safely, knowing that it’s either incomplete or empty.

    Example snippet

    // generates really long string with the entire alphabet
    var str = new Array(100).fill('abcdefghijklmnopqrstuvwxyz').join(' ');
    
    // defines the last char you want to consider
    var len = 65;
    
    // splits the string at that length + 1
    var words = str.slice(0, len + 1).split(/s+/);
    
    // discards last element, which is either empty or incomplete
    words.pop();
    
    // only full alphabets will be displayed
    console.log(words);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search