I would like to display a URL in a table while restricting it to a specific length. Being a URL, it would be nice to preserve the most meaningful parts which tend to be the beginning and end. This functionality can be seen when viewing long URLs in the Firebug 'Net' panel.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I have a very simple solution. I had a similar requirement for a dashboard page:
"We need a URL shortener function that returns a 50 character string, the beginning without http or https and include 32 characters, then an ellipsis, and then the last 15 characters."
So, the shortUrl function needed to take in the long URL, Get the last 15 characters - slice from long url's length (same as last character) minus 15 to get start of slice to the end. Clip off http/https start - I used replace(), Get the next 32 characters - substr(), and then Return new start + ellipsis (...) + end:
This is a quick and dirty solution but it has been working well for me so far and can be easily updated to any individual preferences. It's broken into two functions for readability and reuse.
This function makes use of the
shortString
function shown below. It shortens a URL to less than or equal to the specified length (l) while preserving the beginning and end of the URL and truncating at preferred characters (' ', '/', '&').This function starts at the beginning of a string (or end, if reverse=true) and, once it reaches an acceptable length, starts looking for preferred stop characters to truncate at. If no stop characters are found before the specified length (l) is reached, the string is returned truncated to the max length.
Example
I have created a method to work both for urls and url-encoded local file paths.
Some examples: