javascript 先頭の文字だけを大文字に変換する
- 作成日 2022.09.27
- 更新日 2022.10.14
- javascript
- javascript
javascriptで、先頭の文字だけを大文字に変換するサンプルコードを記述してます。
環境
- OS windows11 home
- ブラウザ chrome 106.0.5249.103
先頭の文字だけを大文字に変換する
先頭の文字だけを大文字に変換するには「slice」で先頭の文字だけ取得して大文字に変換して、「slice」で残りの文字を小文字にしたものを結合します。
console.log(change('mebee')) // Mebee
console.log(change('meBEE')) // Mebee
console.log(change('MEBEE')) // Mebee
function change(str){
if (typeof str !== 'string' || !str) return str;
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
};
変換されていることが確認できます。
サンプルコード
以下は、実行ボタンをクリックすると、テキストフォームに入力した文字の最初だけを大文字にするだけのサンプルコードとなります。
※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
window.onload = () => {
btn.onclick = () => {
foo.innerHTML = change(txt.value)
}
}
const change = (str) => {
if (typeof str !== 'string' || !str) return str;
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-green-500 text-lg mr-auto">実行結果</h1>
<p id="foo" class="font-semibold text-lg mr-auto"></p>
<input
class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="txt" type="text">
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
変換されていることが確認できます。
-
前の記事
Fork コミットidを確認する 2022.09.27
-
次の記事
git configに設定されている値を一覧で確認する 2022.09.27
コメントを書く