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.