4
I have a rather large string and would like to check if an excerpt of it house with a regex. The problem is that this stretch is in the middle of the string, in a very specific position. As I will have to do this several times (different strings, different regexes and different positions) I would like this check to be done efficiently, without having to:
Make a substring, which would create new strings unnecessarily:
var sub = str.substring(pos); // Cria um novo objeto, potencialmente bem grande regex.exec(sub);
or:
Do the search globally, which not only traverses parts of the string that do not interest me (i.e. those before the desired position) but also may not give me the result I want at all (e.g. : if there is an intersection between a previous match and the part of the string that interests me):
var resultado = regex.exec(str); // Assumindo que regex possui a flag g while ( resultado && resultado.index < pos ) resultado = regex.exec(str); if ( resultado.index == pos ) ...
Is it possible to do this? The usual methods of marriage (String.match
, RegExp.test
and RegExp.exec
) do not have parameters to specify the position of the string from which to start the execution, and even the String.search
does not have this option. There is some other way?
Note that the flag
/y
not supported by all browsers– Mariano
@Mariano De facto. This flag has been used in Firefox for years, but has only been standardized by ES6. Currently all modern desktop browsers support - including Edge, but excluding IE in all its versions. On mobile platforms, only iOS 10 for now... I will update the answer with this information.
– mgibsonbr