i wanted build js function concatting list of arguments valid path (since not sure whether part of path given or without slashes)
this function:
concatpath = function() { var path = ""; for(var = 0; < arguments.length; i++) { path += arguments[i].replace("(\\|/)$|^(\\|/)", "") + "/"; } return path; }
the used regex matched beginning , ending slashes , backslashes on http://regexpal.com function not work (regex not match). furthermore, chrome states
syntaxerror: invalid regular expression: /()$|^()/: unterminated group
when use regex
(\\)$|^(\\)
however, using regex
(\\)$|^(\\)
works fine.
is late or did missed special?
thanks in advance!
leo
you should use regular expression literal (/.../
) instead of string literal ('...'
or "..."
) in call replace
. strings have own interpretation of backslashes kicks in before regular expression constructor gets crack @ it, need level of quoting.
match 1 backslash, regular expression literal: /\\/
match 1 backslash, regular expression in string: '\\\\'
but in regex literal, have put backslashes in front of forward slashes, since forward slashes delimiter whole thing:
path += arguments[i].replace(/(\\|\/)$|^(\\|\/)/, "") + "/";
or, if you're married use of strings reason, should work:
path += arguments[i].replace("(\\\\|/)$|^(\\\\|/)", "") + "/";
as side note, when alternatives single characters, (x|y)
overkillish; can use character classes: [xy]
. in case this:
path += arguments[i].replace(/[\\\/]$|^[\\\/]/, "") + "/"; path += arguments[i].replace("[\\\\/]$|^[\\\\/]", "") + "/";
Comments
Post a Comment