Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
Text editor implementation Javascript and HTML

I am trying to create a text editor where users can highlight parts of their input from a content editable div and style it. I used indexes and substring method to modify only the highlighted text. For example, if the input is "helloworld" and they highlight "owo". The re-created text would be "hell" + <span>owo</span> + "rld" and add styling to that span. However, if the user tries to edit the text again, my indexes gets messed up because now the text I am getting is "hell<span>owo</span>rld" instead of "helloworld". I believe this indexing and substring method is not ideal for this kind of problem. Can someone suggest a different method I should try? Below is my code for getting the selected indexes and replacing the text inside the div.

    //function to get indexes of the highlighted text
    function getSelectionIndexes() {
        var start, end;
        if(window.getSelection){
            start = window.getSelection().anchorOffset;
            end = window.getSelection().focusOffset;
        }
        return {
            start: Math.min(start,end),
            end: Math.max(start,end),
            selectedText: window.getSelection().toString()
        };
        
    }
    
    //function to re-format the text and insert it into the div content
    function replaceText(className){
        const text = $('#textarea').html();
        const { start, end, selectedText} = getSelectionIndexes();
        if(start == end) return;

        const beforeText = text.substring(0,start);
        const afterText = text.substring(end);
        
        const beforeElement = document.createElement("span");
        beforeElement.innerHTML = beforeText;

        const selectedElement = document.createElement("span");
        selectedElement.innerHTML = selectedText;
        selectedElement.classList.add(className);

        const afterElement = document.createElement("span");
        afterElement.innerHTML = afterText;
        $('#textarea').html('');
        $('#textarea').append(beforeElement);
        $('#textarea').append(selectedElement);
        $('#textarea').append(afterElement);
        
    }
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda