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
- Tách từ bằng
string.split(" "). - Chuyển toàn bộ về lowercase:
toLowerCase(). - Vòng lặp: viết hoa ký tự đầu
sentence[i][0].toUpperCase()+ nối phần còn lạislice(1). - 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