带有转义斜杠的 JavaScript 正则表达式不会替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4674237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript regex with escaped slashes does not replace
提问by Radek Simko
Do i have to escape slashes when putting them into regular expression?
将斜杠放入正则表达式时是否必须转义斜杠?
myString = '/courses/test/user';
myString.replace(/\/courses\/([^\/]*)\/.*/, "");
document.write(myString);
Instead of printing "test", it prints the whole source string.
它不打印“test”,而是打印整个源字符串。
See this demo:
看这个演示:
回答by Reid
Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.
你的正则表达式是完美的,是的,你必须转义斜杠,因为 JavaScript 使用斜杠来表示正则表达式。
However, the problem is that JavaScript's replace
method does not perform an in-place replace. That is, it does not actually change the string -- it just gives you the result of the replace.
但是,问题在于 JavaScript 的replace
方法不执行就地替换。也就是说,它实际上并没有改变字符串——它只是给你替换的结果。
Try this:
尝试这个:
myString = '/courses/test/user';
myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "");
document.write(myString);
This sets myString
to the replaced value.
这将设置myString
为替换值。
回答by rajesh_kw
/[\/]/g
matches forward slashes./[\\]/g
matches backward slashes.
/[\/]/g
匹配正斜杠。/[\\]/g
匹配反斜杠。
回答by Brett Zamir
Actually, you don't need to escape the slash when inside a character class as in one part of your example (i.e., [^\/]*
is fine as just [^/]*
). If it is outside of a character class (like with the rest of your example such as \/courses
), then you do need to escape slashes.
实际上,您不需要像示例的一部分那样在字符类中转义斜杠(即,[^\/]*
就像 一样很好[^/]*
)。如果它在字符类之外(就像您的其他示例一样\/courses
,例如),那么您确实需要转义斜杠。
回答by Anon.
string.replace
doesn't modify the original string. Instead, a returns a new string that has had the replacement performed.
string.replace
不修改原始字符串。相反, a 返回一个执行了替换的新字符串。
Try:
尝试:
myString = '/courses/test/user';
document.write(myString.replace(/\/courses\/([^\/]*)\/.*/, ""));
回答by Maxim Mazurok
Note, that you don't have to escape /
if you use new RegExp()
constructor:
请注意,/
如果使用new RegExp()
构造函数,则不必转义:
console.log(new RegExp("a/b").test("a/b"))