微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 JavaScript 将 Title 转换为 URL Slug?

如何使用 JavaScript 将 Title 转换为 URL Slug?

概述

标题转换为 URL Slug 也称为“Slugify”标题。 URL Slug 是指本身具有描述性且易于阅读的标题。它附加到页面的 URL 上,该 URL 讲述当前页面,因为 slug 是自我描述的。因此,使用 JavaScript 将标题转换为 slug 可以使用某些 JavaScript 函数来实现,例如 toLowerCase()、replace()、trim()。

算法

convert=()=>{}
  • 第 3 步 - 访问 id 为“document.getElementById(“title”)”.value 的第一个输入标记的值并将该值存储在变量中。

document.getElementById('title').value;
  • 步骤 4 - 使用字符串的“toLowerCase()”函数将从标题接收到的值转换为小写字母。 “t”是接收标题的变量。

t.toLowerCase();
t.trim();
  • 第 6 步 - 使用带有模式的“replace()”函数,用“-”破折号替换标题的所有空格

title with “-” dash, using “replace()” function with a pattern
t.replace(/[^a-z0-9]+/g, '-');
  • 第 7 步 - URL Slug 已准备就绪,显示在浏览器屏幕上。

document.getElementById('urlSlug').value = slug;

示例

在此示例中,我们从用户获取标题作为输入。当用户输入任何标题并单击按钮时,将触发 Convert() 函数,该函数标题值更改为小写,然后将标题的所有前导和尾随空格更改为小写。然后,在给定标题中,空格将替换为破折号 (-),并且 URL Slug 将显示在浏览器只读输入标记上。

<html lang="en">
<head>
   <title>Convert title to URL Slug</title>
</head>
   <body>
      <h3>Title to URL Slug Conversion</h3>
      <label>Title:</label>
      <input type="text" id="title" value="" placeholder="Enter title here"> <br />
      <label>URL Slug:</label>
      <input type="text" id="urlSlug" style="margin:0.5rem 0;border-radius:5px;border:transparent;padding: 0.4rem;color: green;" placeholder="Slug will appear here..." readonly><br />
      <button onclick="convert()" style="margin-top: 0.5rem;">Covert Now</button>
      <script>

         // This function converts the title to URL Slug
         convert = () => {
            var t = document.getElementById('title').value;
            t = t.toLowerCase(); //t is the title received
            t = t.trim(); // trim the spaces from start and end
            var slug = t.replace(/[^a-z0-9]+/g, '-'); // replace all the spaces with "-"
            document.getElementById('urlSlug').value = slug;
            document.getElementById('urlSlug').style.border="0.1px solid green";
         }
      </script>
   </body>
</html>

在上面示例的输出中,用户输入的标题为“教程点文章”。单击“立即转换”后,标题将转换为 URL Slug,即“教程点文章”。其中使用 trim() 函数删除尾随空格,并用连字符替换空格。

结论

统一资源定位器 (URL) Slug 有助于提高页面搜索排名。因此,URL Slug 必须位于 URL 中,并且由于 URL 中的所有单词都是小写,因此标题也首先转换为小写。要注意 URL 中的 slug,只需获取网站的任何文章博客或任何其他内容,观察 URL 的端点,如果它出现在句子中,那么它将以与我们在上面的例子。

以上就是如何使用 JavaScript 将 Title 转换为 URL Slug?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐