We all know the little toolbar buttons to insert something into a textarea, like BBCode, Wiki markup or HTML tags (fun fact: GitHub doesn't have a toolbar). One of the resources I used once was this German site but there are many more. I was wondering, how much of this nifty, widespread code could be squished into 140 bytes.

Currently, this is 159 bytes and I'm looking for your help. One thing I could do is to remove a.focus(); and +b.length but doing so I will loose a major feature. I'm looking for other ways to make this smaller.

Updated, thanks. Here is another idea to save 5 9 bytes, but this will replace the first occurrence of a selected substring instead of the selected one: g=a.value;a.value=g.replace(g=g.slice(a[d],f),b+g+c);.

I already thought of that, even tried to think up a clever idea with a replace s/(.{x})(.{y})(.{z})/$1b$2c$3/, but it was considerably longer than the original. Even using exec instead of replace doesn't help there.

I also tried to use a regular expression but it's, well, complicated. Here is the shortest solution I found so far: a.value=a.value.replace(RegExp('([\\s\\S]{'+a[d]+'})([\\s\\S]{'+(f-a[d])+'})'),'$1'+b+'$2'+c);. The most reliable solution is this, but it's 3 bytes longer than using split: g=a.value;a.value=g.slice(0,a[d])+b+g.slice(a[d],f)+c+g.slice(f);.

I found a reliable (does not work well when nothing is selected) but very short solution based on a regular expression. It works for all positions in the string including the first character. It's short but still to long (164 163 bytes).

function(a,b,c,d,e,f){a.focus(d='selection');e=d+'End';d+='Start';f=a[e];a.value=a.value.replace(/|/g,function(g,h){return a[d]-h?f-h?g:c:b});a[e]=a[d]=f+b.length}
// The following version also works when nothing is selected (168 bytes)function(a,b,c,d,e,f){a.focus(d='selection');e=d+'End';d+='Start';f=a[e];a.value=a.value.replace(/|/g,function(g,h){return(a[d]-h?g:b)+(f-h?g:c)});a[e]=a[d]=f+b.length}

I give up. The following version (132 bytes) does not care about setting the cursor position at all. But it works in all cases mentioned above (when the first character or nothing is selected). Anyway, new ideas are welcome.