带有转义斜杠的JavaScript正则表达式不会替换 [英] JavaScript regex with escaped slashes does not replace

查看:128
本文介绍了带有转义斜杠的JavaScript正则表达式不会替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将它们放入正则表达式时是否必须转义斜杠?

Do i have to escape slashes when putting them into regular expression?

myString = '/courses/test/user';
myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);

它不打印test,而是打印整个源字符串。

Instead of printing "test", it prints the whole source string.

参见此演示:

http://jsbin.com/esaro3/2/edit

推荐答案

你的正则表达式是完美的,是的,你必须转义斜杠,因为JavaScript使用斜杠来表示正则表达式。

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.

试试这个:

myString = '/courses/test/user';
myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);

这将 myString 设置为替换值。

这篇关于带有转义斜杠的JavaScript正则表达式不会替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆