JavaScript 如何将标题转换为URL Slug
概述
将标题转换为URL Slug也称为”Slugify”标题。URL Slug是指一个自我描述且易于阅读的标题。它附加到页面的URL上,以告知当前页面的内容,因为Slug是自我描述的。因此,可以使用JavaScript中的某些函数(如toLowerCase()、replace()、trim())将标题转换为Slug。
步骤
- 步骤1 - 创建一个带有两个输入标签的HTML页面,并将它们分别添加为”id”属性,第一个输入元素将接收用户输入的标题,另一个标签将显示URL Slug。还要创建一个HTML按钮””,并添加一个onclick()事件,其中包含一个名为”convert()”的函数。
-
步骤2 - 现在创建一个作为HTML页面内部JavaScript的”convert()”箭头函数。
convert=()=>{}
- 步骤3 - 使用id为”title”的第一个input标签的值,使用”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”。点击“convert now”按钮后,标题会转换为URL Slug,即“tutorial-point-articles”。在这个过程中,使用trim()函数删除了尾部空格,并用连字符替代了空格。
结论
统一资源定位符(URL)Slug有助于提高页面的搜索排名。因此,在URL中必须使用URL Slug,并且URL中的所有单词都应为小写。要注意URL中的Slug,只需获取任何文章、博客或网站的其他内容,观察URL的末尾部分,如果它是一个完整的句子,则应按照上例中所示的格式写入。