Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển câu sang Title Case (viết hoa chữ cái đầu) trong JavaScript


Title Case a Sentence

Viết hoa chữ cái đầu mỗi từ, các chữ còn lại viết thường.

Thuật toán

  1. Tách từ bằng string.split(" ").
  2. Chuyển toàn bộ về lowercase: toLowerCase().
  3. Vòng lặp: viết hoa ký tự đầu sentence[i][0].toUpperCase() + nối phần còn lại slice(1).
  4. Ghép lại bằng join(" ").

Ví dụ

<html> <body> <script> function titleCase(string) { var sentence = string.toLowerCase().split(" "); for(var i = 0; i < sentence.length; i++){ sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1); } document.write(sentence.join(" ")); return sentence; } titleCase("tutorix is one of best e-platforms"); </script> </body> </html>

Kết quả

Tutorix Is One Of Best E-platforms