Runtime Terror
Runtime Terror

Reputation: 6742

JavaScript Regex for overwriting file path

I want to replace file path with gulp task. For that I need to write a Regex:

I have a folder structure ../assets/js/components/main/main.component.html, where I need to replace the whole path, ../assets/js/components/**/, with an empty string. So after applying a Regex on my example I should get only the html file, e.g.: main.component.html

The Regex should match only the path ../assets/js/components/ with only one level of subfolder, e.g.: ../assets/js/components/**/. Path with only ../assets/js/components/ should not match and path with more than one subfolder neither ../assets/js/components/main/shouldnotmatch/

I wrote already one Regex:

^..\/assets\/js\/components\/(?:\[^\/\]+\/?)*$

The problem here is, that It selects everything. Any idea how to fix this?

EDIT:

More examples:

../assets/js/components/main/ => ../assets/js/components/main/ ../assets/js/components/ => should not match ../assets/js/components/test/index.html => ../assets/js/components/test/ ../assets/js/components/main/shouldnotmatch/shouldnotmatch.html => ../assets/js/components/main/ ../assets/js/components/some_components.html => should not match ../assets/js/components/1.html => should not match

Upvotes: 1

Views: 319

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

It seems you want to avoid matching HMTL/HTM files when used at the location of subfolder.

You may use a lookahead to add that restriction and use

^\.\.\/assets\/js\/components\/(?![^\/]+\.html?$)[^\/]+\/?

See the regex demo

Details

  • ^ - start of string
  • \.\. - 2 dots
  • \/assets\/js\/components\/ - a literal string /assets/js/components/
  • (?![^\/]+\.html?$) - immediately to the left of the current location, there can't be:
    • [^\/]+ - 1 or more chars other than /
    • \.html? - .html or htm
    • $ - at the end of the string
  • [^\/]+ - 1 or more chars other than /
  • \/? - 1 or 0 /s

Upvotes: 1

Related Questions