去掉英文链接中的单词 the

更新日期: 2019-06-22 阅读次数: 5758 字数: 270 分类: SEO

为了让网页 URL 的英文链接更简短,更具可读性,我觉得有必要过滤掉其中的单词 the。

几种情况

  • 前缀: the-xxx
  • 后缀: xxx-the (翻译接口有 bug 时,可能出现)
  • 中间: xxx-the-xxx

处理逻辑

  • 先处理中间的情况:替换 '-the-' 为 '-'
  • 再处理前缀的情况:以 'the-' 开头的,去掉
  • 最后处理后缀的情况:以 '-the' 结尾的,去掉

实现代码

在原有的生成英文网页链接的代码逻辑中加上上述三个逻辑。

修改后的逻辑为:

slugify: function (text) {
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/\-the\-/g, '-')       // 先处理中间的情况:替换 '-the-' 为 '-'
    .replace(/^the\-/g, '')         // 再处理前缀的情况:以 'the-' 开头的,去掉
    .replace(/\-the$/g, '')         // 最后处理后缀的情况:以 '-the' 结尾的,去掉
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
},

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式