timrosenthal timrosenthal - 6 months ago 21
Javascript Question

shorten encodeURIComponent(document.title)

I'm using

onclick="window.location.href"
as part of a
mailto
link and I wanted to know if there is a way to restrict the document title to a specific length. More specifically, our tab titles have
|
and I would like to end the subject line at the first
|
. Here is the code I'm using.

<a style="color:#b9b9b9" href="mailto:?subject=&body=:%20http%3A%2F%2Fwww.taconic.com" title="Share this page" onclick="window.location.href='mailto:?subject=Check out this page:%20' + encodeURIComponent(document.title) + '&body=' + encodeURIComponent(document.URL); return false;"><i class="fa fa-envelope"></i></a>

Answer

More specifically, our tab titles have | and I would like to end the subject line at the first |.

Replace document.title with the following:

document.title.replace(/^([^|]+)\|.*$/, '$1')

In the code above we use String.prototype.replace. The first argument is a regular expression, where

  • the first ^ character stands for the beginning of the line;
  • [^|] is a set of all characters, except the | character;
  • \| is the | character escaped with backslash to distinct from the "OR" expression syntax;
  • .* means any character(the dot) repeated zero or more times(the star);
  • $ character stands for the end of the line.

The second argument is the replacement string, where '$1' points to the first group in the regular expression(parentheses).

In other words, the code extracts all characters from the beginning of document.title until the | character.

You can make the string even shorter with String.prototype.substr, for example:

document.title.replace(/^([^|]+)\|.*$/, '$1').substr(0, 20)

The substr method in the code above substracts 20 characters from the beginning of the result returned by the replace method. We chain the substr call, because the replace method returns a String.

Comments