javascript 文字列の最後にある空白を除去する
- 作成日 2021.01.15
- 更新日 2022.08.03
- javascript
- javascript

javascriptで、ES2019より追加されたをtrimEndを使用して、文字列の最後にある空白を除去するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
trimEnd使い方
trimEndを使用すると、文字列の最後にある空白を除去することが可能です。
文字列.trimEnd();
実際に、最後にある空白だけが除去されるかを確認してみます。
console.log(' hello world '.trimEnd() );
実行結果をみると、最後にある空白だけが除去されていることが確認できます。

全角の空白も除去されます。
console.log(' hello world '.trimEnd() );
実行結果

正規表現を使用
正規表現を使用して除去することも可能です。
console.log(' hello world '.replace(/\s+$/g,'') );
実行結果

パフォーマンスは、ブラウザによります。
全ての空白を除去する場合は、以下をご参考下さい。
サンプルコード
以下は、
「実行」ボタンをクリックすると、フォームに入力した値の後方にある空白のみを除去する
サンプルコードとなります。
※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 = () => {
// 空白を除去
foo.value = foo.value.trimEnd(); // document.getElementById('foo');を省略
}
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 type="text" id="foo" class="form-control">
</div>
<div class="row">
<button id="btn" type="button" class="btn btn-warning">
実行
</button>
</div>
</div>
</body>
</html>
後方の空白のみが削除されていることが確認できます。

-
前の記事
puma+nignx エラー「sockets/puma.sock failed (13: Permission denied)」の対処法 2021.01.15
-
次の記事
CentOs7 redisをインストールする手順 2021.01.15
コメントを書く