JavaScript >> Javascript 文檔 >  >> Tags >> API

將字符串中每個單詞的首字母大寫 [JavaScript]

這篇簡短的文章向您展示瞭如何大寫 字符串中的第一個字母或字符串中的所有單詞(標題大小寫 ) 在 javascript 編程語言中。

如果您希望以語法正確的方式顯示單個單詞或整個句子的大寫,則將字符串中的第一個字母大寫很有用。

將字符串轉換為 title case - 這就是每個單詞在包含多個單詞的字符串中大寫的地方 - 對於格式化用於文章或頁面標題的文本很有用。

將字符串中的第一個字母大寫

首先,這裡是如何僅將字符串中的第一個字母大寫。

此示例作為可重用函數提供,可將其複制並粘貼到您的代碼中並投入使用。

// Reusable function to capitalize first letter in a string
function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

// Testing the above function
console.log(capitalizeFirstLetter('foo')); // Will print 'Foo'

那麼上面發生了什麼? 首先,第一個字符(在索引 0 ) 使用 charAt() 從字符串中檢索 方法並使用 toUpperCase() 將其設為大寫 方法。

然後,它與字符串的其餘部分連接,sliced 在索引 1 刪除第一個字符(所以它不會重複,因為我們已經將第一個字符大寫了)。最後,為了更好地衡量,字符串的其餘部分被轉換為toLowerCase() 以防它還沒有。

簡單!

將字符串中每個單詞的首字母大寫(大寫)

這裡是如何大寫每個 字符串中的單詞 ——那是每一系列字符的第一個字母,用空格隔開。

這個函數還有一些東西,所以我將在代碼中留下註釋而不是在最後解釋它。

// Reusable function to capitalize first letter of every word in a string
function titlecase(str) {

    // Split the string at each space.  This will create an array containing each word in the string.
    var splitStr = str.toLowerCase().split(' '); 

    // Loop through the words in the string 
    for (var i = 0; i < splitStr.length; i++) {
        // Capitalize the first word in each using the same method as in the previous example
        // The result replaces the original word in the splitStr array
        splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
    }

    // Join the now-capitalized words in the array back into a single string, separated by spaces, and return it
    return splitStr.join(' '); 
}

// Testing the above function
console.log(titlecase('foo bar')); // Will print 'Foo Bar'

在標題中使用 CSS

如果您只是想格式化文本以供顯示,您可以使用 CSS 以標題大小寫顯示字符串,而無需使用 JavaScript 處理它:

<style>
    .titlecase {
        text-transform: capitalize;
    }
</style>

<p class="titlecase">capitalize me!</p>

當在網絡瀏覽器中呈現時,文本將由 CSS text-transform 大寫 屬性。


Tutorial JavaScript 教程
  1. 在奇點生活的一天

  2. 真棒動畫複選框 CSS 切換 - 日/夜模式

  3. 使用事件驅動的 Javascript 驗證表單

  4. 為什麼我要從 React 切換到 Cycle.js

  5. 將您的博文添加到您的 Github README

  6. 使用 React Native 和 Firebase 上傳文件(第 1 部分)

  7. PHP使用包含在頁面上設置活動鏈接

  1. Angular 應用的 6 大安全最佳實踐

  2. Node.js 中的診斷第 2/3 部分

  3. 項目在數組中嗎?

  4. 通過示例了解 JavaScript 閉包

  5. 了解解構(對象和參數)

  6. 設置動態創建的 tr 標籤的 id

  7. 前端大師有哪些必看課程?

  1. JS控制台技巧(如何在控制台中使用Css)

  2. Node.js &Express.js 字體區分

  3. 構建單頁應用程序,無需構建 API。 🤯

  4. 為什麼你應該關心你 Npm 安裝的東西