0

I am trying to create basic text editor using Rxjs and javascript. I have created a button named 'B' in .html file which when clicked makes a selected text from textarea bold.How do I give styling to that selected text in textarea using javascript in boldcontent() function below? Also, if a selected text is entirely bold then how can I make bold button auto-selected?

I know that this is very basic doubt but I am a beginner in javascript. It would be really great if someone can help me in understanding this.



let btnbold=document.getElementById('btnbold');
let textarea=document.getElementById('text_area_id');


fromEvent(btnbold,'click').subscribe(()=>boldcontent());

let boldcontent=()=>{
let selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);


}```
student
  • 39
  • 1
  • 7
  • https://stackoverflow.com/a/4705882/262708 – Lil Devil Mar 16 '21 at 20:24
  • I assume you are using a textarea control to create your editor? If you were to be using a regular div take a look at the following. https://stackoverflow.com/questions/20880271/make-selected-text-bold-unbold. btn.onclick = () => { document.execCommand('bold'); } – NateScript Mar 16 '21 at 20:44

1 Answers1

0

let's focus on mutating the text and leave rxjs aside. In your boldcontent you have:

let selection = textarea.value.substring(
  textarea.selectionStart,
  textarea.selectionEnd,
);
      

But this only contains the selected text. What you really want to do is to replace the whole text in your textarea with the selected part bracketed by two asterisks ** (given markdown is your preferred method here):

  const {value, selectionStart, selectionEnd} = textarea;
  const newValue =
        value.slice(0, selectionStart) + // (1) 
        "**" + 
        value.slice(selectionStart, selectionEnd) + // (2)
        "**" +
        value.slice(selectionEnd, value.length); // (3)
  textarea.value = newValue;

(1) this gets the substring before the selected text

(2) this is the selected text

(3) this is the remainging substring after the selection

However this is a very limited example and far from production ready. A proper implementation would also ensure that each ** has a corresponding closing tag. Bold text that is partially selected should be properly merged with the new selection etc... To cover all these edge cases you could create new questions here on SO.

kruschid
  • 759
  • 4
  • 10