Help us understand the problem. What is going on with this article?

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

経緯

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away