JavaScript正则表达式替换 - 转义斜杠 [英] JavaScript regex replace - escaping slashes
问题描述
myString ='/ courses / test / user' ;
myString.replace(/ \ / courses\ /([^ \ /] *)\ /.*/,$ 1);
document.write(myString);
而不是打印测试,它打印整个源字符串。
看到这个演示:
http://jsbin.com/esaro3/2/edit
你的正则表达式是完美的,是的,你必须逃避斜杠,因为JavaScript使用斜杠表示正则表达式。
但是,问题是JavaScript的替换为
方法不执行就地替换。也就是说,它实际上并没有改变字符串 - 它只是给你取代的结果。
尝试这样:
myString ='/ courses / test / user';
myString = myString.replace(/ \ / courses\ /([^ \ /] *)\ /.*/,$ 1);
document.write(myString);
将 myString
设置为替换的值。
Do i have to escape slashes when putting them into regular expression?
myString = '/courses/test/user';
myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
Instead of printing "test", it prints the whole source string.
See this demo:
http://jsbin.com/esaro3/2/edit
Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.
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.
Try this:
myString = '/courses/test/user';
myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
This sets myString
to the replaced value.
这篇关于JavaScript正则表达式替换 - 转义斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!