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

244
Vistas
How can I find an exact substring using String.prototype.search?

I have this code:

const ids = '[2][13]';
const myid = '1';

const result = ids.search('[' + myid + ']') != -1 ? 'found' : 'not found';
console.log(result);

this is returning found whereas it should be returning not found because id #1 is not present. However since [13] has a 1 in it then it misinterprets it. How can I fix this so it searches for the EXACT value match?

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

0

what your are trying to do can be achieved with .indexOf this returns index of exact match occurance or -1 in not found

you can check details about indexOf here indexOf

var ids = '[2][13]';
var myid = '1';

var r = ids.indexOf('['+myid+']') != -1 ? 'found' : 'not found';
console.log(r)

about 4 years ago · Juan Pablo Isaza Denunciar

0

For the String.prototype.search() you are using a RegExp which treats some characters as reserved for the pattern matching - angle brackets for your case.

ids.search(/\[1\]/);

If you are assembling the expression manually, the backslash is also treated differently because it's parsed twice. The first parsing is for a conversion of string into a RegExp object (which uses \ for special characters such as \n, \t, ...) and the second parsing is when the regular expression is utilized.

If you escape it only once (\[) it'll create a regular expression of [ which is a reserved character, therefore you need to use \\[ so that the first parsing converts it to \[ and then a regular expression \[ i.e. the literal value of [ is used for pattern matching.

var myid = 1;
'[2][13]'.search(new RegExp(`\\[${myid}\\]`));
// or as pointed out in the comments:
'[2][13]'.search(`\\[${myid}\\]`);
about 4 years ago · Juan Pablo Isaza Denunciar

0

search converts any string you give it to a regular expression. [] is special in regular expressions, it defines a character class.

I suspect you want includes, not search, which looks for exactly what you pass it.

const result = ids.includes("[" + myid + "]") ? "found" : "not found";

(Or with a template literal:

const result = ids.includes(`[${myid}]`) ? "found" : "not found";

)

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