jeudi 4 mai 2017

Make a live editor that formats text & colors

I want to make a live text editor that will allow all text surrounded in square brackets to be highlighted as code. [example]

How can I pull the text from the editing <div> and replace all [text] like so with a code element?

Eg: Replace [word] with <code>[word]</code>.

This is what I have in regards to the editing window:

<div contenteditable="true" id="edit">
    The big <code>[color]</code> fox jumped over the lazy <code>[animal]</code>.
</div>

The big [color] fox jumped over the lazy [animal].

I've made this little bit of JS but it doesn't do anything:

EDIT = document.getElementById("edit");

EDIT.onkeypress = function(event) {
    if (event.keyCode === 221) {
        var text = EDIT.innerText;
        EDIT.innerHTML = text.replace(/\[([\w\s]+)]/g, "<code>[$1]</code>");
    }
};

As you can see, I'm trying to use a little bit of regex to do it.

Other than this, I can't think of a way to accomplish what I want. And even this doesn't work.

Thanks.




Aucun commentaire:

Enregistrer un commentaire