File & Path

Relative Path

Matches relative file paths (./, ../, or path/to/file).

Try it in RegexPro →

Available in

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("^(\\.{1,2}\\/)?([^\\/\\0]+\\/)*[^\\/\\0]+$", "");
const input = "./src/index.ts";
const match = input.match(re);
console.log(match ? match[0] : null);

Uses `String.prototype.match`, which returns the first match or null.

Pattern

regexengine-agnostic
^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$

Raw source: ^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$

How it works

`^(\.{1,2}\/)?` optionally matches `./` or `../` prefix. `([^\/\0]+\/)*` matches zero or more directory segments. `[^\/\0]+$` matches the final file segment.

Examples

Input

./src/index.ts

Matches

  • ./src/index.ts

Input

../parent/file.js

Matches

  • ../parent/file.js

Input

file.txt

Matches

  • file.txt

Common use cases

  • •Import resolution
  • •Build tools
  • •Path normalization

Related patterns