2

I created a function a while back that capitalizes a string. The function applies a regular expression to determine if the first alphanumeric character is preceded by a non-alphanumeric character. The search method returns the index of the first alphanumeric character, should that be the case. Otherwise, the function simply converts the first character of the string to an uppercase character.

function capitalize(string: string) {
  const match = string.search(/(?<=[^[a-z]|[0-9]\s])[a-z]|[0-9]/i);
  const index = match === -1 ? 0 : match;

  const characters = string.toLowerCase().split('');
  characters[index] = characters[index].toUpperCase();

  return characters.join('');
}

However, it turns out that this breaks in Safari, because the regular expression relies on a positive look-behind, and Safari does not support that, as far as I can tell.

How could I rewrite this regular expression, so that it works in Safari as well (no look-behind)?

I know that this can be done in multiple steps, but I would much prefer to use just one regular expression if that is possible.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I think your current regex doesn't actually work. If the first character of the string is a alphanumeric already, it won't be matched since it's not preceded by anything. Is this really what you want? – Bergi Jul 13 '22 at 00:21
  • 2
    Would a simply word boundary work for you? – Bergi Jul 13 '22 at 00:22
  • @Bergi Yes. Because, if it does not match anything, then `index` is set to 0 anyway. – Mihkel Pajunen Jul 13 '22 at 10:48
  • You were right, @Bergi. I could simply use `/[a-z]|[0-9]/`. I would use a word boundary if it did not also include the character for underscore. Anyway, I tested it out and it does yield the correct index. – Mihkel Pajunen Jul 13 '22 at 11:08

0 Answers0