Build a Random Quote Machine - character limit problem

Hi everyone,

I’ve nearly finished the Build a Random Quote Machine challenge but I’m stuck on a strange problem. No matter what I set the character limit to in the JavaScript some of the tweets say they’re over Twitter’s character limit of 140. I believe it has to do with the message string being URL encoded, but I don’t know how to fix it, or even if it’s possible!

My CodePen for the challenge is here: Alidek: Random Quote Machine Challenge

Any solutions, feedback or advice will be gratefully received!

Edit: moved post to the General forum as it seemed more appropriate than the Project Feedback forum.


I don’t know much about Twitter but I do know that there is a 140 character limit.

I suppose you could break it into more than one tweet. Or there are services that will break tweets up for you - I don’t know if they can be interfaced with an API. Or truncate it.

I just sent it to twitter and let the user deal with it. OK, not the best solution, but hey, I was just starting out.

Thanks for your quick response, ksjazzguitar.

I’ve already truncated it but it didn’t work because I was truncating the original string, not the string encoded into the URL. It’s calculating the character count on the URL string query, not the text itself. So the tweet:

Whenever I have an idea I write it down, even if it’s not a very good idea. Sometimes the bad… #quotes (133 characters)

Ends up as…

Whenever%20I%20have%20an%20idea%20I%20write%20it%20down%2C%20even%20if%20it%27s%20not%20a%20very%20good%20idea.%20Sometimes%20the%20bad…%20%23quotes% (151 characters).

I tried setting the character limit after decodeURIComponent() but that didn’t work. I need to find out how to truncate the URL encoded string, not the original string. I’m assuming there’s no way to send the tweet without it being encoded into a URL string. :frowning:


Woo hoo! I fixed it!

I needed to use encodeURIComponent(phrase) first to turn it into the URL string complete with %20 for each space.

I then checked if the resulting string was longer than 99 characters (so that there are spare characters for the hashtag and URL).

If it was larger than that I used
var num = phrase.lastIndexOf(’%20’);
phrase = phrase.substring(0,num);

to find the last URI encoded space in the phrase and truncate it at that point, so it wasn’t cutting the string off part way through a word.

The CodePen is working for me now. If anyone else finds an error please let me know so I can fix it before submitting this challenge!


I’m no expert here, but mine seems to be calculating it based on the length of the string, not the URI encoding.

But I used a different approach:"" + text + ";hashtags=" + hashtags, "width=500,height=300");
1 Like

Thanks again, ksjazzguitar! I’ll have to try your approach. It looks a lot neater than my code!