Js
字符串正则转译
起先是由于这个错误
然后发现 \ 也不能作为字符串的结尾
The \ is a escape character for regular expressions, and also for javascript strings. This means that the javascript string “\“ will produce the following content :. But that single \ is a escape character for the regex, and when the regex compiler finds it, he thinks: “nice, i have to escape the next character”… but, there is no next character. So the correct regex pattern should be \. That, when escaped in a javascript script is “\\“.
需要 escape 的字符
[
]
\
^
*
+
?
{
}
|
(
)
$
.
解决方式:
https://www.npmjs.com/package/escape-string-regexp
export function escapeStringRegexp(string: string) {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
// Escape characters with special meaning either inside or outside character sets.
// Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
}