反斜杠 - 正则表达式 - Javascript [英] Backslashes - Regular Expression - Javascript
问题描述
我想构建一个JS函数,将一个参数列表连接到一个有效的路径(因为我无法确定该路径的一部分是否带有斜杠)
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)
这是函数:
concatPath = function() {
var path = "";
for(var i = 0; i < arguments.length; i++) {
path += arguments[i].replace("(\\|/)$|^(\\|/)", "") + "/";
}
return path;
}
使用的RegEx匹配 http://regexpal.com
但该功能无法正常工作(RegEx不匹配)。
此外,Chrome状态
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
语法错误:正则表达式无效:/()$ | ^()/:未终止组
当我只使用RegEx
when I just use the RegEx
(\\)$|^(\\)
但是,使用RegEx
However, using the RegEx
(\\)$|^(\\)
工作正常。
是否太晚或者我错过了什么特别的东西?
Is it too late or did I missed something special?
提前致谢!
Leo
推荐答案
你应该使用正则表达式文字( /.../
)而不是字符串文字('...'
或...
)调用替换
。字符串有自己的反斜杠解释,在正则表达式构造函数得到破解之前就会启动,所以你需要额外的引用级别。
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.
匹配一个反斜杠,定期expression literal: / \\ /
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("(\\\\|/)$|^(\\\\|/)", "") + "/";
作为附注,当您的替代品是单个字符时,(x | y)
过于苛刻;你可以使用字符类: [xy]
。在这种情况下你得到这个:
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("[\\\\/]$|^[\\\\/]", "") + "/";
这篇关于反斜杠 - 正则表达式 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!