How to give replace RegExp in editable div using Javascript?

2

I have an editable% color where I can capture the whole text inside it. Dai I want that in every occurrence of a certain word that word be replaced by another. Very simple.

The code I tried did not work. It itself works only that the output does not work (which in the case is the input itself). But if it's put in div for example, it works.

JS

    function teste(){
        var campo = document.getElementById('editorid').textContent;
        var docrg = /palavra/g; // procurar por 'palavra' sem ignorar case
        campo.replace(docrg, "outrapalavra"); // replace 'palavra' por 'outrapalavra'
    }
    document.getElementById('botao').addEventListener('click',teste,false);

HTML

    <div id="editorid" contenteditable="true"></div>
    <button id="botao">clica</button>

CSS (optional only to show border)

    #editorid{
            width: 500px;
            height: 500px;
            border: 1px solid black;
            padding: 10px;
    }

Note: This problem is just a module of a text editor I'm trying to do.

    
asked by anonymous 24.12.2014 / 12:35

2 answers

4

Here's a suggestion:

I think most of the code is easy to understand except for ExpReg.

(palavra\-chave)(?!<) in parts would be:

() - group to capture text
palavra-chave - the text we want to capture where I escaped the - that in regex can mean between "a" and "c". (in this case I think it would not be necessary, but by habit I put it). (?!<) - this means that what was before can not be followed by < . I put this character so that a new <span> tag for example will prevent the check.

document.querySelector('button').addEventListener('click', function () {
    var editavel = document.querySelector('div[contenteditable="true"]');
    var novoConteudo = '<span class="format">palavra-chave</span>';
    editavel.innerHTML = editavel.innerHTML.replace(/(palavra\-chave)(?!<)/g, novoConteudo);
});
.format {
    color: red;
    font-style: italic;
}
span.format {
    color: #aad;
}
<div contenteditable="true">
    <p>texto texto texto palavra-chave. texto palavra-chave, texto texto.</p>
</div>
<button>Mudar!</button>
    
24.12.2014 / 12:50
1

I think an assignment is missing on this line:

campo.replace(docrg, "outrapalavra"));

Looking like this:

var aux = campo.replace(docrg, "outrapalavra");

Or it may also be the additional parenthesis in the first statement quoted ...

    
24.12.2014 / 12:40