缩短 encodeURIComponent(document.title)

shorten encodeURIComponent(document.title)

我正在使用 onclick="window.location.href" 作为 mailto link 的一部分,我想知道是否有办法将文档标题限制为特定长度。更具体地说,我们的标签标题有 |,我想在第一个 | 结束主题行。这是我正在使用的代码。

<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>

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

document.title 替换为以下内容:

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

在上面的代码中我们使用了String.prototype.replace。第一个参数是正则表达式,其中

  • 第一个^字符代表行首;
  • [^|]是所有字符的集合,除了|字符;
  • \| 是用反斜杠转义的 | 字符,以区别于 "OR" 表达式语法;
  • .*表示任何字符(点)重复零次或多次(星号);
  • $字符代表行尾

第二个参数是替换字符串,其中''指向正则表达式中的第一组(括号)。

换句话说,代码提取从 document.title 开始直到 | 字符的所有字符。

您可以使用 String.prototype.substr 使字符串更短,例如:

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

上面代码中的substr方法是从replace方法返回的结果的开头减去20个字符。我们chain调用substr,因为replace方法returns一个String.