JavaScript regex with escaped slashes does not replace

纵然是瞬间 提交于 2019-12-04 16:12:08

问题


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


回答1:


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.




回答2:


/[\/]/g matches forward slashes.
/[\\]/g matches backward slashes.




回答3:


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.




回答4:


string.replace doesn't modify the original string. Instead, a returns a new string that has had the replacement performed.

Try:

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


来源:https://stackoverflow.com/questions/4674237/javascript-regex-with-escaped-slashes-does-not-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!