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

194
Vistas
Replace text in textarea after string match and key event

Problem - Unable to replace text within textarea when a string match is found

Expected outcome - For specific string "Dave" to get replaced with longformText variable when keyup event occurs

Current outcome - .replace() method on e.target.value string is not replacing text when a match of "Dave" is found. I want the replacement to happen the moment a match is found or after entering a space

Heres my code so far - I'm watching for every textarea elements on page

let longformText = 'my name is Dave';
let currentEl;
const regex = /Dave/i;

window.onclick = (e) => {
    currentEl = e.target;
    currentEl.addEventListener('change', (e) => {
        if (e.target.value.includes('Dave')) {
            console.log(true);
            e.target.value.replace(regex, longformText);
        }
    });
};
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <p>Enter some text</p>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <script src="snippet.js"></script>
    </body>
</html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

First of all, I would be careful about how to apply eventlistener to elements. What your does code right now, is apply a eventlistener on every element you click on. I would instead, set an eventlistener for onchange or input on the textarea elements themselves. Then trigger an event when the word dave appears. I've written a working example below :)

let longformText = 'my name is Dave';
let currentEl;
const regex = /Dave/i;
const textAreaElements = document.querySelectorAll("textarea");

textAreaElements.forEach(textArea => {
  textArea.addEventListener("input", e =>{
    let value = e.target.value;
    console.log(value)
    if(regex.test(value)){
      console.log("Match!");
      let newValue = value.replace(regex, longformText);
      e.target.value = newValue;
    }
  })
})
<body>
        <p>Enter some text</p>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <script src="snippet.js"></script>
    </body>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are not assigning value to your current Element. Here I updated a little JS code please check.

let longformText = 'my name is Dave';
let currentEl;
const regex = /Dave/i;

window.onclick = (e) => {
    currentEl = e.target;
    currentEl.addEventListener('change', (e) => {
        if (e.target.value.includes('Dave')) {
            console.log(true);
            e.target.value = e.target.value.replace(regex, longformText);
        }
    });
};
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <p>Enter some text</p>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <textarea name="" id="" cols="30" rows="10"></textarea>

        <script src="snippet.js"></script>
    </body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is the JS i came up with, along with a codepen.

https://codepen.io/webdevjones/pen/LYQPZaM

let longformText = 'my name is Dave';


const textAreas = document.querySelectorAll('textarea')

for(let i = 0; i < textAreas.length; ++i){
    textAreas[i].addEventListener('keyup', (e) => {
        textAreas[i].value = textAreas[i].value.replace(/Dave/i, longformText)
    })
}

I do enjoy how your requirements cause an infinite loop of Daves each keypress!

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