无效的正则表达式:无重复错误

Mis*_*ybe 1 javascript regex unicode counter

I am trying to make an app that counts how many times each character occurs in a given string. So for example, in the string "hello 12355" it should match with all the numbers past 1, and not with the "hello" part. However, when I try to run the code, I get this in the console:

"Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat at new RegExp ()"

When I change xy to anything past 92, however, the code runs fine. From what I've read about this error, it means that you have to double backslash some characters because they mean something in Regexp. However, I can't double backslash the Unicode variable without affecting all of the Unicode values. Can anyone help?

Here is my code:

var occArray = [];
var occChars = [];

var xy = 50;

for (i = xy; i < 100; i++) {
    var unicodeChar = String.fromCharCode(i);
    var counter = new RegExp(unicodeChar, 'g');
    var occurence = "hello 12355";
    var occ = (occurence.match(counter) || []).length;

    occArray.push(occ);     
    occChars.push(unicodeChar);
}
    alert(occArray);
    alert(occChars);
Run Code Online (Sandbox Code Playgroud)

小智 5

我认为这是因为您要传递的某些字符unicodeCharRegex中的特殊字符(在您的错误中,?这是63)。请考虑检测它是否是特殊字符,如果是特殊字符,则可以在将其传递给Regex之前在其前面添加反斜杠。

可能对您有帮助。