javascript 文字列内から指定した文字列の後ろにある1文字を抽出する
- 作成日 2022.10.12
- 更新日 2022.10.28
- javascript
- javascript

javascriptで、文字列内から指定した文字列の後ろにある1文字を抽出するサンプルコードを記述してます。抽出の流れは、指定した文字列の存在する位置を取得して、それ以降の文字列を切り出して、最後に後ろにある1文字を取得するために、検索対象の文字列の長さから「-1」した場所の文字列を抽出します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.63
文字列内から指定した文字列の後ろにある1文字を抽出
文字列内から指定した文字列の後ろにある1文字を抽出するには、
1. 「indexOf」で文字列の位置を取得
2. 見つかった位置以降の文字を「substring」で切り出し
3. 「指定した文字」の長さにより取得する1文字の位置を決定する
ことで可能です。
const str = "abcde"
let selectStr = "bcd"
// 位置を取得
console.log( str.indexOf(selectStr) ) // 1
let position = str.indexOf(selectStr);
// 位置から「+1」した位置から文字を取得
console.log( str.substring( position + 1 ) ); // cde
console.log(selectStr.length); // 3
// 対象の文字列の長さをから一番後ろの文字を取得
console.log( str.substring( position + 1 )[selectStr.length - 1 ] ); // e
// 文字列「bc」でテスト
selectStr = "bc"
position = str.indexOf(selectStr);
console.log( str.substring( position + 1 ) ); // cde
console.log(selectStr.length); // 2
console.log( str.substring( position + 1 )[selectStr.length - 1] ); // d
selectStr = "b"
position = str.indexOf(selectStr);
console.log( str.substring( position + 1 ) ); // cde
console.log(selectStr.length); // 1
console.log( str.substring( position + 1 )[selectStr.length - 1] ); // c
後ろに文字が存在しない場合は、「undefined」が返ります。
const str = "abcde"
let selectStr = "e"
let position = str.indexOf(selectStr);
console.log( str.substring( position + 1 )[selectStr.length - 1 ] ); // undefined
前の1文字
ちなみに、前の1文字を取得する場合は、以下となります。
const str = "abcde"
let position = str.indexOf('bc');
console.log( str.substring(position - 1, position) );
// a
サンプルコード
以下は、
「取得」ボタンをクリックすると、フォームに入力された文字列に対して、別のフォームに指定した文字列の後ろにある1文字を取得して表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-25" style="margin-top:150px">
<h2><span class="badge badge-success">結果</span></h2>
<label class="form-label" for="txt1">文字列</label>
<input id="txt1" type="text" class="form-control" />
<label class="form-label" for="txt2">指定した文字列</label>
<input id="txt2" type="text" class="form-control" />
<button id="btn" type="button" class="btn mt-1 btn-success">
取得
</button>
</div>
<script>
// クリックイベントを登録
btn.onclick = () => { hoge() };
const getAfter = (str) => {
let position = str.indexOf(txt2.value);
return str.substring( position + 1 )[ txt2.value.length - 1 ];
}
const hoge = () => {
document.getElementsByClassName('badge')[0].textContent = getAfter(txt1.value);
}
</script>
</body>
</html>
取得されていることが確認できます。

-
前の記事
Google ドキュメント 辞書を開くショートカットキー 2022.10.11
-
次の記事
PostgreSQL ロールのパスワードを変更する 2022.10.12
コメントを書く