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

122
Vistas
Wrap tags [start] [end] around selected text in textarea with Javascript

I have a textarea where users can input text. With a button, they should be able to wrap a selected text in this textarea with custom tags [start] [end].

<button onclick="addTags();">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

Example: If the text in the textarea is for example "1 2 3" and user marks "2" and clicks the button the result in the textarea should be "1 [start]2[end] 3".

I am trying no to get a piece of javascript to work, that will do this for me.

I played around with "window.getSelection()". So the question is: What is the right approach for my function?

function addTags() {
...
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Cut the text up: before the selection, the selection, after the selection. Then reassemble with tags.

document.getElementById("add-tag").onclick = () => {
  let txt = document.getElementById("user-input");
  const before = txt.value.substring(0, txt.selectionStart);
  const sel = txt.value.substring(txt.selectionStart, txt.selectionEnd);
  const after = txt.value.substring(txt.selectionEnd);
  txt.value = `${before}[start]${sel}[end]${after}`;
}; 
<button id="add-tag">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

TODO: Handle case where nothing is selected.-

about 4 years ago · Juan Pablo Isaza Denunciar
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