反斜杠 - 正则表达式 - 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
(\)$|^(\)
但是,使用正则表达式
(\)$|^(\)
工作正常.
是不是太晚了,还是我错过了一些特别的东西?
Is it too late or did I missed something special?
提前致谢!
狮子座
推荐答案
您应该使用正则表达式字面量 (/.../
) 而不是字符串字面量 ('...'
或 "..."
) 在对 replace
的调用中.字符串对反斜杠有自己的解释,反斜杠在正则表达式构造函数得到破解之前就开始使用,因此您需要额外的引用级别.
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("(\\|/)$|^(\\|/)", "") + "/";
作为旁注,当你的替代品是单个字符时,(x|y)
是矫枉过正;您可以只使用字符类 ([xy]
).在这种情况下,您会得到:
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("[\\/]$|^[\\/]", "") + "/";
这篇关于反斜杠 - 正则表达式 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!