1

In Twitter, if you post a link in tweet, for example, http://stackoverflow.com/questions/8699459/get-title-content-via-link-in-rails

the URL automatically changes to a shorten one: enter image description here

And the correspongding Html is:

  <span class="invisible">http://</span>
  <span class="js-display-url">stackoverflow.com/questions/8699</span>
  <span class="invisible">459/get-title-content-via-link-in-rails</span>

(the http:// and long partis hidden)

So How can I achieve this? I believe it's something with JS? or How should I approach this with Rails?

Many Thanks!!!

ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • I think this is the answer you are looking for http://stackoverflow.com/questions/3282100/ruby-on-rails-generating-bit-ly-style-uuids – Tyler Apr 24 '13 at 13:55
  • Uhm....I'm not looking for that kind of link shortner, just want to hide some part of a URL – ZK Zhao Apr 24 '13 at 13:59
  • Perhaps this is more what you want? http://stackoverflow.com/questions/6338870/how-to-implement-a-short-url-like-urls-in-twitter – Tyler Apr 24 '13 at 14:08

1 Answers1

0

I think this is what you're looking for or at least close to it.

aHref.innerHTML = aHref.match(/([\w\d\-_]*\.)+(\w*$|\w*\/[\w\d]*)/)[0];

In short; this ignores the protocol:// and takes every string ending in "." (for sub domains) until it reaches the last item (could be "com", could be "uk" as in "co.uk") denoted by either "$" (end of the string) or a "/" followed by an alphanumeric string. With the resulting string it replaces the innerHTML or displayed content value.

So for example: "http://test.couch.com/333/fire" would become "test.couch.com/333"

Edit: I should add that I've only accounted for

A-Za-z0-9 and -_

in the url up to the "/" and only

A-Za-z0-9

For the remainder.

Edit 2: Using in Rails controller

The same principle applies but without the innerHTML since it's a DOM element property

 url = url.match(/([\w\d\-_]*\.)+(\w*$|\w*\/[\w\d]*)/).first

The line above will do the same thing as the javascript or at least will create the same shortened url.

If you mean how to use with the a helper:

shortUrl= url.match(/([\w\d\-_]*\.)+(\w*$|\w*\/[\w\d]*)/).first
link_to  shortUrl, url
CBusBus
  • 2,321
  • 1
  • 18
  • 26
  • Thats what I'm looking for. And how can I use it in controller? I mean, in twitter, the Link is auto-shortened when posted out, but I have no idea in doing this – ZK Zhao Apr 29 '13 at 03:44
  • @cqcn1991 I've added an example f its use in a Rails controller, although it's almost identical to the original example. – CBusBus Apr 30 '13 at 11:02