如何使用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的結尾,如果它是一個句子,那麼它將以我們在上面示例中看到的相同格式編寫。