javascript 文字列の後方に文字を加える
- 作成日 2021.02.27
- 更新日 2022.08.08
- javascript
- javascript
javascriptで、padEndを使用して、文字列の後方に文字を加えるサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
padEnd使い方
「padEnd」を使用すると、文字列の後方に文字を加えることが可能です。
文字列.padEnd(長さを指定 [, 埋め込みたい文字列])
padEnd使い方
const str = 'mebee';
// 埋める文字列を指定して後方に、指定した文字数を埋めることができます
console.log(
str.padEnd(10, "e") // mebeeeeeee
);
空白を埋めることも可能です。「”」は空白をわかるように使用してます。
const str = 'mebee';
// 空白を追加して、10文字に合わせる
console.log(
'\"' + str.padEnd(10) + '\"'
// "mebee "
);
文字数が少ない場合
指定した長さが文字数より少ない場合や「0」や「マイナス」を指定した場合は、元の文字列がそのまま返ります。
const str = 'mebee';
console.log(
str.padEnd(0, "e"), // mebee
str.padEnd(1, "e"), // mebee
str.padEnd(-10, "e") // mebee
);
また、指定した長さより、文字数が足らない場合、足りている分だけで埋められます。
const str = 'mebee';
console.log(
str.padEnd(6, "abc"), // mebeea
str.padEnd(7, "abcde") // mebeeab
);
日本語とサロゲートペア文字
日本語は、アルファベットと同じように動作しますが、
const str = 'あいうえお';
console.log(
str.padStart(7, "か") // かかあいうえお
);
通常の2バイトで1文字で表すところを、4バイトで1文字となるサロゲートペア文字だと、
1文字の長さが「1」ではなく「2」としてカウントされます。
const str = '😂😁';
console.log(
str.padEnd(5, "!"), // 😂😁!
str.padEnd(6, "!"), // 😂😁!!
str.padEnd(5, "😻"), //😂😁�
str.padEnd(6, "😻") // 😂😁😻
);
実行結果
文字列以外に使用
文字列以外に使用するとエラーが発生するため、使用前に文字列であるか判定してから使用すると
エラーは回避できます。
const num = 123;
if(typeof num === 'string'){
console.log(
num.padEnd(5, "0") // 00123
);
}
前方に文字を加える
逆に「前方に文字を加える」場合は、以下を参考にして下さい。
サンプルコード
以下は、
「実行」ボタンをクリックすると、指定した長さで指定した文字列を後方に追加して表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
.main {
margin: 0 auto;
margin-top: 200px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 30px;
}
</style>
<script>
const hoge = () => {
// フォームに入力された文字列の指定した文字列 + 指定したテキストを末尾に追加
const str= txt.value.padEnd(11, " World") ; // document.getElementById('txt');を省略
// 表示
result.innerHTML = str;
}
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
}
</script>
<body>
<div class="main container">
<h2><span id="result" class="badge bg-info">後方に文字列追加</span></h2>
<div class="mb-3">
<input id="txt" type="text" class="form-control">
</div>
<div class="row">
<button id="btn" type="button" class="btn btn-warning">
実行
</button>
</div>
</div>
</body>
</html>
後方に文字列が追加されていることが確認できます。
-
前の記事
TortoiseGit エラー「git.exe not correctly set up()」が発生した場合 2021.02.27
-
次の記事
TortoiseGitでブランチを作成する手順 2021.02.27
コメントを書く