3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでtextareaの選択範囲の前後に文字列を挿入する

Last updated at Posted at 2018-07-11

経緯

redmineでtextileで書いていて、<pre>タグ内で一部を赤文字にするなどして強調させたい時があって毎回、</notextile>%{color: red}<notextile>赤文字</notextile>%<notextile>をコピペしていたが、めんどくさくなったのでjavascriptにした。

ソース

var textarea = document.querySelector('textarea');
var pos_start = textarea.selectionStart;
var pos_end = textarea.selectionEnd;
var val = textarea.value;
var range = val.slice(pos_start, pos_end);
var beforeNode = val.slice(0, pos_start);
var afterNode = val.slice(pos_end);
var insertNode = " [前] " + range + " [後] ";
textarea.value = beforeNode + insertNode + afterNode;

使い方

  1. " [前] "、" [後] "を任意の値に修正
  2. ChromeでF12を押してJavaScriptコンソールを開く
  3. テキストエリアの挿入したい個所を選択
  4. 選択した状態で上記のソースをJavaScriptコンソール上にコピペ&Enterして実行
  5. ブックマークレット化など後はお好きにどうぞ

javascriptで選択範囲の前後に文字列挿入.png

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?