Search code examples
javascriptjestjsregular-language

what does two backslashs mean in jest's configuration


now i am learning jest to write unit tests. i have read part of the document of jest and some code on github about jest configuration, and i found that the option moduleNameMapper could be defined like:

"moduleNameMapper": {
    "\\.(jpg|jpeg|png|gif)$": "<rootDir>/__mocks__/fileMock.js",
    ".*\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
}

but i cannot understand what does "\\" mean in the configuration ?

it seems that two backslashs in a regular expression cannot match any file or directory.

i just wonder if such configuration can match like "aaa.jpg", "src/images/bbb.jpg", "src/less/style.config.less", etc or not ?


Solution

  • A backslash is an escape character in a regular expression and a string literal.

    In the regex \. means a literal full stop character. Since the regex is inside a string literal, the \ part of that needs escaping for the string parser.

    alert("My regex is: " + "\\.(jpg|jpeg|png|gif)$")