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

234
Vistas
How can I escape special characters in regex and Javascript

I'm developing a simple chat bot and I'm having some trouble escaping special characters using .replace - I might be missing the obvious but the code below doesn't work and I can't figure out why. Any ideas?

To clarify, this code works and does what I want it to do without the .replace line but I need it so if a user types ? or ! etc it won't matter.

    var know = {
<!--General Phrases-->  
"Hi": "Hello! &#128075",
"Hey": "Hello! &#128075",
"Hello":"Hello &#128075 How can I help?",    
"how are you":"Not bad, thanks!",
"Bye":"Have a nice day!",
"Goodbye":"See you later!", 

<!--Directory-->
"Help": `You can find help by searching below or by clicking <a href='https://www.page.com/news' target="_blank">here</a>`,
"contact":  `You can contact us by clicking <a href='https://www.page.com/contact' target="_blank">here</a>`,
"About": `You can find our About Us page by clicking <a href='https://www.page.com/about' target="_blank">here</a>` 
};

function goo() {
 var userBox = document.getElementById('userBox');
 var userInput = userBox.value;
 var chatLog = document.getElementById('chatLog');
 var chatLogContent = "";

 if (!userInput) {
     chatLogContent = ''
 }

 var hasKeyword = false;

 for (var key in know) {
      if (userInput.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g,"").match(new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')))  {{
          hasKeyword = true;
          break;
      } else {
          hasKeyword = false;
      }
 }

if (hasKeyword) {
    chatLogContent += know[key] + "<br>"; //or use know.key
} else {
    chatLogContent += "No results found. Please enter another search term below.<br>";
}

var server = document.createElement('div');
server.setAttribute('class', 'server');
server.innerHTML = chatLogContent;
document.getElementById('chatLog').innerHTML = '';
chatLog.appendChild(server);
}

UPDATE: This has been solved. Please see Wiktor Stribiżew's answer in the comments.

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

0

On this line:

if (userInput.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g,"").match(new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')))  {{

you remove spaces (there is a space in the character class in /[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g). That is why your regex (that you build with new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')) matches only when the string is equal to key, it expects the key in between whitespaces or start/end of string.

You need to remove the space from replacement and apply this operation both on the input and key:

if (userInput.replace(/[.,\/#!$%^&*;:{}=\-_`~()\\]/g,"").match(new RegExp('(^|\\s)'+key.replace(/[.,\/#!$%^&*;:{}=\-_`~()\\]/g,"")+'(\\s|$)', 'i')))  {{

Note ^ and ; need no escaping. I also added a backslash to the special char character class.

Note there is no need to turn the case to lower, you can simply pass the i case insensitive flag to regex.

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