0

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?

Stephen
  • 41
  • 9
  • It's `\d` for numbers, not `/d` – Phil Nov 07 '18 at 04:47
  • Right. Yes. Edited. All those brackets and slashes getting to me. Still doesn't work though. – Stephen Nov 07 '18 at 04:57
  • 1
    You need to escape the all backslashes when using a string in the `RegExp` constructor, including `\d`, ie `\\d` – Phil Nov 07 '18 at 04:59
  • Damn, simple as that - it worked. Thanks muchly. – Stephen Nov 07 '18 at 05:09
  • Btw, for `{1,}` there is a `+` operator, and for `{0, 1}` is `?`. And to fulfill @Phil comment - even when you passing a string to `.match` method you should also use double escaping as it goes through `RegExp` constructor in that case. – extempl Nov 07 '18 at 05:18

1 Answers1

0

Answered by Phil in comments above - I was failing to properly escape all special characters when using the RegExp constructor.

Stephen
  • 41
  • 9