javascript - solo - probar expresiones regulares
Cadena de escape para usar en expresiones regulares de Javascript (1)
Short ''n Sweet
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[/]//]/g, ''//$&''); // $& means the whole matched string
}
Ejemplo
escapeRegExp("All of these should be escaped: / ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: // /^ /$ /* /+ /? /. /( /) /| /{ /} /[ /] "
Instalar
Disponible en npm como escape-string-regexp
npm install --save escape-string-regexp
Nota
Ver MDN: Guía de Javascript: Expresiones regulares
Otros símbolos (~ `! @ # ...) PUEDEN escaparse sin consecuencias, pero no se requiere que lo sean.
.
.
.
.
Caso de prueba: una url típica
escapeRegExp("/path/to/resource.html?search=query");
>>> "//path//to//resource/.html/?search=query"
La respuesta larga
Si va a usar la función que se encuentra arriba, al menos en el enlace a esta publicación de desbordamiento de pila en la documentación de su código para que no parezca un vudú alucinante difícil de probar.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// / ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+/|-_;:''/",<.>".match(/[/#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn''t matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "//"
, "^"
, "$"
, "|"
]
// I choose to escape every character with ''/'
// even though only some strictly require it when inside of []
, regex = RegExp(''['' + specials.join(''//') + '']'', ''g'')
;
escapeRegExp = function (str) {
return str.replace(regex, "//$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
Posible duplicado:
¿Hay una función RegExp.escape en Javascript?
Estoy tratando de construir una expresión regular de javascript basada en la entrada del usuario:
function FindString(input) { var reg = new RegExp('''' + input + ''''); // [snip] perform search }
Pero la expresión regular no funcionará correctamente cuando la entrada del usuario contenga un ?
o *
porque se interpretan como regex especiales. De hecho, si el usuario coloca un desequilibrado (
o [
en su cadena, la expresión regular ni siquiera es válida.
¿Cuál es la función javascript para escapar correctamente todos los caracteres especiales para su uso en expresiones regulares?