Backslashes - Regular Expression - Javascript

I wanted to create a JS function that combines an argument list into a valid path (since I couldn’t be sure if part of the path was given with or without a slash)

This is the function:

concatPath = function() {
    var path = "";
    for(var i = 0; i < arguments.length; i++)   {
        path += arguments[i].replace("(\\|/)$|^(\\|/)", "") + "/";
    }
    return path;
}

Used by RegEx matched all leading and trailing slashes and backslashes at http://regexpal.com But the function does not work correctly (RegEx does not match). Chrome also indicates

SyntaxError: Invalid regex: / () $ | ^ () /: Unterminated group

when I just use RegEx

 (\\)$|^(\\)

However, using RegEx

 (\\)$|^(\\)

works great.

Too late or did I miss something special?

Thanks in advance!

Leo

+5
source share
2 answers

(/.../) ('...' "...") replace. , , , .

, : /\\/

, : '\\\\'

, - :

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

, - , :

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

, , (x|y) ; : [xy]. :

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

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

... [ ]. \ javascript \\\\, , .

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

/^[\\\/]|[\\\/]$/g.

s = 'c:\\folder\\'
console.log(s.replace(/^[\\\/]|[\\\/]$/g, ''))
+3

All Articles