regex - Is there a RegExp.escape function in Javascript? -
i want create regular expression out of possible string.
var usersstring = "hello?!*`~world()[]"; var expression = new regexp(regexp.escape(usersstring)) var matches = "hello".match(expression);
is there built in method that? if not, people use? ruby has regexp.escape
. don't feel i'd need write own, there's gotta standard out there. thanks!
the function linked above insufficient. fails escape ^
or $
(start , end of string), or -
, in character group used ranges.
use function:
regexp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); };
while may seem unnecessary @ first glance, escaping -
(as ^
) makes function suitable escaping characters inserted character class body of regex.
escaping /
makes function suitable escaping characters used in js regex literal later eval.
as there no downside escaping either of them makes sense escape cover wider use cases.
and yes, disappointing failing not part of standard javascript.
Comments
Post a Comment