Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

regex - Backslashes - Regular Expression - Javascript

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)

This is the function:

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

The used RegEx matched all beginning and ending slashes and backslashes on http://regexpal.com But the function does not work properly (RegEx does not match). Furthermore, Chrome states

SyntaxError: Invalid regular expression: /()$|^()/: Unterminated group

when I just use the RegEx

 (\)$|^(\)

However, using the RegEx

 (\)$|^(\)

works fine.

Is it too late or did I missed something special?

Thanks in advance!

Leo

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 a character class ([xy]). In which case you get this:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...