Trying to do a JS function that will generate a new name in the form '{name} (n)' where n is the next integer value from a given list of names. E.g. given 'Name', 'Name (1)', 'Name (2)' the function should return 'Name (3)'. Obviously using regex functionality is the way to go, but I'm having trouble with the brackets. Here's what I've got
utilitiesService.getNextUniqueName = function (name, arr) {
var uniqueName = name;
var max = -1;
var matchStr = new RegExp('^' + name + '( \\((\d{1,})\\)){0,1}');
arr.forEach(function (element) {
var match = element.match(matchStr);
if (match && match.length > 0) {
if (match[2] == null) {
max = max < 0 ? 0 : max;
} else {
max = max < Number(match[2]) ? Number(match[2]) : max;
}
}
});
if (max >= 0) {
uniqueName = uniqueName + ' (' + String(max + 1) + ')';
};
return uniqueName;
}
The parameters 'name' - a string giving the base name for the list, 'arr' - an array of strings giving existing names (not all will even match the base name). The match works but the problem is that the returned array 'match' never contains the numeric part that should be given by the innermost '(/d{1,})'. In fact it only ever contains undefined for the array elements 1 and 2. What am I doing wrong?