What this code does is find the indices of and in a string , then with substring, I only take the part inside the brackets."["
"]"
Then I draw them in a canvas
according to the if:
- a string that is without the content of the brackets (also including the removal of the brackets themselves),
- and another where only the content of the brackets is displayed.
And everything normal, but sometimes, very rarely, unexpectedly I get the error:
Nothing to repeat error
Why does this happen?
var b = this.name.indexOf("["); // Busca el [
var c = this.name.indexOf("]"); // Busca el ]
var mostrar = this.name.substring(b, c + 1);
mostrar = mostrar.replace(/[\[\]']+/g,'');
var d = c - b;
if(d > 1 && nameDraw && mostrar != '') {
var t = this.name.replace(new RegExp(mostrar, 'g'), '');
t = t.replace(/\[.*?\]/g, '');
drawText(this.x - 4, this.y, t, this._nameSize, false);
drawText(this.x, this.y - 62, mostrar, this._nameSize, false);
}
Nothing to repeat is a syntax error within your regular expression. It means that there is a quantifier (
*
,?
,+
,{m,n}
) that is in a position where it has nothing to repeat. It usually happens with a quantifier at the beginning of the expression, or with one quantifier following another (invalid).For your specific case, it happens because you are dynamically generating a regex from some text without escaping the special characters. When the user enters something like
this.name="Genera [error???]"
, you are trying to generate a regex with"error???"
, which is an invalid expression.To generate a literal regex from a string, you have to escape it using this function
Code
Let's forget about the problem of escaping the text, let's simplify.
We are going to use the regex
/\[([^\]]*)\]/
.\[
- literal bracket.(
...)
- Capturing group. Generates a reference to the text it matched.Coincides with:
[^\]]*
- A character, any except']'
, repeated (*
) 0 or more times.That is, " matches all characters other than
]
".\]
- literal bracket.In the replace() , instead of passing a string, we can pass an anonymous function that will be called to evaluate the regex replacement.
The anonymous function receives as parameters the string that the regex matched, and then a parameter for each capture made by each group.
In the regex
/\[([^\]]*)\]/
we use 1 set of parentheses, to capture the text that is inside the brackets. In other words, the function will receivem
the text with brackets as the first parameter ( ), andmostrar
the same text as the second parameter ( ), but without the brackets.The result of the function is what will actually be used in the string replacement. That's why we always return
''
(empty text), so that the brackets are removed from the original string. It's the same as doing,texto.replace( regex, '');
, but evaluating the match in the function.