I have seen questions and answers for using variables with RegEx like this:
var re = new RegExp(yyy, 'g');
xxx.match(re);
How do I add the caret and the dollar sign for an exact match?
I am iterating through an array: [-10, 0, 10] as search values. So, I am trying to do something like this:
var re = new RegExp("^" + data[i] + "$", 'g');
If I am searching an array of [-10, 0, 10] and if I search for 0, I get all three. I need to search for only 0 with this: /^0$/
Here is my entire code with test cases. I am trying to find unique items using RegEx / match.
function nonUniqueElements(data){
var arrForDeletion = [];
var strData = data.join(",");
for(var i = 0; i < data.length; i++){
var re = new RegExp(data[i], 'g');
console.log("re: " + re);
var matches = strData.match(re);
if(matches.length === 1){
arrForDeletion.push(data.indexOf(data[i]));
}
}
if(arrForDeletion.length > 0){ // If there are unique items in the input array, do not include them in the returned array.
var arrReturn = [];
data.forEach(function(item,idx){
if(arrForDeletion.indexOf(idx) === -1){
arrReturn.push(item);
}
});
console.log("arr to be returned:");
console.log(arrReturn);
return arrReturn;
}
else{ // There were no unique items in the input array.
console.log("no unique items:");
console.log(data);
return data;
}
}
/*
nonUniqueElements([1, 2, 3, 1, 3]); // == [1, 3, 1, 3]
nonUniqueElements([1, 2, 3, 4, 5]); // == []
nonUniqueElements([5, 5, 5, 5, 5]); // == [5, 5, 5, 5, 5]
nonUniqueElements([10, 9, 10, 10, 9, 8]); // == [10, 9, 10, 10, 9]
*/
nonUniqueElements([-10,10,0]); // []
/^0$/will match the string"0"and only that string."^" + data[i] + "$". Unless you mean that you want to include "^" and "$" in your match. Maybe you should describe what problem you're trying to solve and we can help more directly.