JavaScript正则表达式替换 - 转义斜杠 [英] JavaScript regex replace - escaping slashes

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

问题描述

  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屋!

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