Skip to content

JavaScript Regex for Path without leading or trailing slashes

I’m struggling to figure out a Regex pattern for JavaScript that will trim a path of it’s preceding and trailing slashes (or hashes/extensions)

For example:

path/
/path
/folder/path/
/folder/folder/path
/folder/path#hash
/folder/path.ext

Should return:

path
path
folder/path
folder/folder/path
folder/path
folder/path

I felt like I was getting close with the following, but it only selects text without any slashes, hashes, or periods.

^([^\/#.]*)(?![#.\/].*$)/gm

I’m trying to use this for Regex in a vuetify text-field validation, if that’s at all helpful.

Result

I ended up with this regex slug

/^(?![#/.$^=*;:&?()[]{}"'><,@!%`~s])(?!.*[#/.$^=*;:&?()[]{}"'><,@!%`~s]$)[^#.$^=*;:&?()[]{}"'><,@!%`~s]*$/

https://regexr.com/66ol9

Answer

This is how it is achieved with no lookbehinds (they are still rejected in Safari :():

^(?![#/.])(?!.*[#/.]$).*

See regex proof. And…

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [#/.]                   any character of: '#', '/', '.'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*                       any character except n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [#/.]                   any character of: '#', '/', '.'
--------------------------------------------------------------------------------
    $                        before an optional n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  .*                       any character except n (0 or more times
                           (matching the most amount possible))