selectionStartは、「 HTMLTextAreaElement 」と「 HTMLInputElement 」のプロパティでinput要素とtextarea要素のテキスト入力カーソルの位置を返します。
「 HTMLInputElement 」要素の注意点は、text、search、URL、tel、password の各入力型にのみ適用されます。それ以外の入力型に selectionStart プロパティを設定すると例外が発生します。
文字の分割をsubstr()で記載しているサイトがありますが、現在では非推奨のため、substringもしくはsliceを使用します。
const btn = document.getElementById('btn');
const target_area = document.getElementById('target');
btn.addEventListener('click', function(){
const start = target_area.selectionStart;
const end = target_area.selectionEnd;
const txt = target_area.value;
target_area.value = txt.substring(0, start) + "<br>" + txt.substring(end);
})
「 element.selectionStart 」で、開始位置を取得できます。カーソルがtextareaの先頭の場合、「 0 」を返します。
また、カーソルの開始位置を設定する際にも使用します。
element.selectionStart = 1;
「 element.selectionEnd 」で、終了位置を取得できます。範囲選択していない場合、「 selectionStart 」と同じ値になります。
また、カーソルの終了位置を設定する際にも使用します。
element.selectionEnd = 1;
範囲選択する場合は、「 selectionStart 」と「 selectionEnd 」をそれぞれ設定します。
「 selectionStart 」が「 selectionEnd 」よりも大きくなった場合、「 selectionEnd 」の位置を取得します。
以下の場合は、2文字目を選択した状態にします。以下の例もアクセスキーでアクセスすると範囲選択された状態を確認することができます。
const btn = document.getElementById('btn');
btn.addEventListener('click', function(){
target_area.selectionStart = 1;
target_area.selectionEnd = 2;
})