Js

字符串正则转译

起先是由于这个错误
image.png
然后发现 \ 也不能作为字符串的结尾
image.png

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 的字符

  1. [
  2. ]
  3. \
  4. ^
  5. *
  6. +
  7. ?
  8. {
  9. }
  10. |
  11. (
  12. )
  13. $
  14. .

解决方式:
https://www.npmjs.com/package/escape-string-regexp

  1. export function escapeStringRegexp(string: string) {
  2. if (typeof string !== 'string') {
  3. throw new TypeError('Expected a string');
  4. }
  5. // Escape characters with special meaning either inside or outside character sets.
  6. // 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.
  7. return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
  8. }