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
This is what I ended up going with:
You should check that the string is longer than the desired length and if it is…
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