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?
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)
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}\\]`);
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";
)