Backslashes - Regular Expression - Javascript

前端 未结 2 897
别那么骄傲
别那么骄傲 2020-11-22 01:57

I wanted to build a JS function concatting a list of arguments to a valid path (since I could not be sure whether a part of the path is given with or without slashes)

<
相关标签:
2条回答
  • 2020-11-22 02:03

    Try this... it's a little easier to follow with the [character classes]. to match a single \ with a javascript string you need \\\\, which may be what's going on.

    new Regexp('^[\\\\/]|[\\\\/]$')

    You can also try the /^[\\\/]|[\\\/]$/g notation.

    s = 'c:\\folder\\'
    console.log(s.replace(/^[\\\/]|[\\\/]$/g, ''))
    
    0 讨论(0)
  • 2020-11-22 02:07

    You should use a regular expression literal (/.../) instead of a string literal ('...' or "...") in the call to replace. Strings have their own interpretation of backslashes that kicks in before the regular expression constructor gets a crack at it, so you need an extra level of quoting.

    Match one backslash, regular expression literal: /\\/

    Match one backslash, regular expression in a string: '\\\\'

    But in a regex literal, you also have to put backslashes in front of the forward slashes, since forward slashes are the delimiter for the whole thing:

    path += arguments[i].replace(/(\\|\/)$|^(\\|\/)/, "") + "/";
    

    Or, if you're married to the use of strings for some reason, this should also work:

    path += arguments[i].replace("(\\\\|/)$|^(\\\\|/)", "") + "/";
    

    As a side note, when your alternatives are single characters, (x|y) is overkillish; you can just use character classes: [xy]. In which case you get this:

    path += arguments[i].replace(/[\\\/]$|^[\\\/]/, "") + "/";
    
    path += arguments[i].replace("[\\\\/]$|^[\\\\/]", "") + "/";
    
    0 讨论(0)
提交回复
热议问题