如何使用JavaScript将标题转换为URL Slug?
概述
将标题转换为URL Slug也称为将标题“Slugify”。URL Slug指的是本身具有描述性且易于阅读的标题。它附加在页面的URL上,用于描述当前页面,因为Slug本身具有描述性。因此,使用JavaScript将标题转换为Slug可以使用某些JavaScript函数来实现,例如toLowerCase()、replace()、trim()。
算法
步骤1 - 创建一个包含两个输入标签的HTML页面,并分别为其添加id属性“title”和“urlSlug”,第一个输入元素将接收用户输入的标题,另一个标签将显示URL Slug。还创建一个带有onclick()事件的HTML按钮“<button>” ,其中包含函数“convert()”。
步骤2 - 现在创建一个作为HTML页面内部JavaScript的“convert()”箭头函数。
convert=()=>{}
步骤3 - 使用id为“document.getElementById(“title”)”.value访问第一个输入标签的值,并将值存储在一个变量中。
document.getElementById('title').value;
步骤4 - 使用字符串的“toLowerCase()”函数将从标题接收到的值转换为小写。“t”是一个接收标题的变量。
t.toLowerCase();
步骤5 - 现在使用“trim()”函数删除标题的前导和尾随空格。
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>
在上面的示例输出中,用户输入的标题为“tutorial point articles”。单击“转换”后,标题将转换为URL Slug为“tutorial-point-articles”。其中,尾随空格使用trim()函数删除,空格用连字符替换。
结论
统一资源定位符(URL) Slug有助于提高页面的搜索排名。因此,URL Slug在URL中是必须的,并且由于URL中的所有单词都小写,因此标题也首先转换为小写。要在URL中查看Slug,只需选择网站的任何文章、博客或其他内容,观察URL的结尾,如果它是一个句子,那么它将以我们在上面示例中看到的相同格式编写。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP