Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!