Skip to content
Advertisement

Jquery/Javascript – Regex – Error only in Safari browser

Used below JS script with regex.

  1. To allow only numbers in input field.
  2. To change currency value with comma like 1,000 or 1,00,000 on user type value in input.

Below codes working in all major browser expect in safari. Getting this error only in safari. Not sure how to fix this regex without affecting other working browsers.

SyntaxError: Invalid regular expression: invalid group specifier name

    $('input.input-num').on('change click keyup input paste',(function (event) {
        $(this).val(function (index, value) {
            return value.replace(/(?!.)D/g, "").replace(/(?<=..*)./g, "");
        });
    }));

    $('input.input-currency').on('change click keyup input paste',(function (event) {
        $(this).val(function (index, value) {
            return value.replace(/(?!.)D/g, "").replace(/(?<=..*)./g, "").replace(/(?<=.dd).*/g, "").replace(/B(?=(d{3})+(?!d))/g, ",");
        });
    }));

Advertisement

Answer

These are the changes you can consider:

  • .replace(/(?!.)D/g, "") – (optional) – since (?!.)D matches any non-digiti chars except dots, it makes sense to define this replacement as .replace(/[^d.]/g, "")
  • .replace(/(?<=..*)./g, "") – this can be re-written to match a dot, then capture all after it and remove all dots in the captured substring: .replace(/.(.*)/, function(x) { return x.replace(/./g, ''); })
  • .replace(/(?<=.dd).*/g, "") – this is easy to fix with a capturing group and a backreference to it in the replacement: .replace(/(.dd).*/, "$1") (note you do not need g since you only expect one replacement here).
Advertisement