Shuffle selected text in <textarea> using JavaScript

When I select some texts on <textarea> with the mouse, how can I shuffle / copy it by clicking on the button?

I was looking for something similar to what I want here on SO, and I saw those using substring , selectionStart and selectionEnd .

I want: when I select some texts with the mouse, it will be shuffled / scrambled when I click on the button, and the rest of the texts on <textarea> that are not selected should remain intact / intact.

I just want to perform an action on selected texts.

It looks more like a rich text editor, for example, when you select some texts, then click the bold button, the selected texts will become bold .

PS It must be shuffled by individual characters.

EDIT: Got it! I just needed to separate the selection line. My code is working now. This is very useful - stack overflow

Unfortunately, IE 9 and below do not support the selectionStart and selectionEnd properties on <input> and <textarea> . Here's the solution that worked for me - stack overflow.site/questions/1400239 / ...

+4
source share
2 answers

You have access to the full text and know the substring in which the selection begins and ends. Try something like this:

 var txtArea = document.getElementById("foo"); var before = txtArea.value.substr(0, txtArea.selectionStart); var selection = txtArea.value.substr(txtArea.selectionStart, txtArea.selectionEnd + 1); var after = txtArea.value.substr(txtArea.selectionEnd, txtArea.value.length); txtArea.value = before + scrambleThisString(selection) + after; 
+1
source

Suppose you name a text field with the identifier content :

 var textarea = document.getElementById('content'); var content = textarea.value; var start = textarea.selectionStart; var end = textarea.selectionEnd; var before = content.slice(0, start); var after = content.slice(end); var selected = content.substring(start, end); selected = shuffleStringByMagic(selected); textarea.value = before + selected + after; 
+1
source

Source: https://habr.com/ru/post/1400238/


All Articles