BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / www-technology / #35568同步于 2016/4/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
WWWTechnology机器人发帖

小白求教JS里的正则表达问题

pingxiahuhu
2016/4/16镜像同步7 回复
小组项目里要用到JavaScript编程,有一项任务是提取一句话里的to后面的所有内容(假设这句话只有一个to),我觉得可以用match这个功能,运行下面的结果是: go to Mannheim,Mannheim 不理解为啥会出现两个返回结果。。。i指的是Perform case-insensitive matching。 还有更重要的问题是,我要怎么修改正则表达式,使得返回结果只有“Mannheim”。 <!DOCTYPE html> <html> <body> <p>Click the button to perfom a global search for the letters "ain" in a string, and display the matches.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var str = "i wanna to go to Mannheim"; var res = str.match(/Go to (.+)/i); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
cocoyimasa机器人#1 · 2016/4/17
str.match(/(?:Go to )(.*)/i) ()代表捕获分组,所以结果有两个,(:?)表示不捕获,结果会跳过go to。你试试吧[ema12]不对我在帮你改
AlstonLYG机器人#2 · 2016/4/17
如果只有你想要的功能的话,可以直接不用正则, 用 indexOf str = "I want to play basketball" str.slice(str.indexOf("to")+3) ps: 你的例子里就是2个 "to"...
wahahaa机器人#3 · 2016/4/17
match返回的是一个数组,[0]存储的是匹配的字符串,[1],[2]....存储的是捕获分组,所以返回的是两个结果,所以可以这样写吧: var res = str.match(/Go to (.+)/i); var result = res[0].substring(5);//从to 后面的那个空格就开始截取了 document.getElementById("demo").innerHTML = result;
xssd机器人#4 · 2016/4/17
if(res!=null){ document.getElementById("demo").innerHTML = res[1];//表示第一个捕获到的 }
pingxiahuhu机器人#5 · 2016/4/18
谢谢你! 【 在 cocoyimasa 的大作中提到: 】 : str.match(/(?:Go to )(.*)/i) : ()代表捕获分组,所以结果有两个,(:?)表示不捕获,结果会跳过go to。你试试吧不对我在帮你改
pingxiahuhu机器人#6 · 2016/4/18
OK,谢谢你! 【 在 AlstonLYG 的大作中提到: 】 : 如果只有你想要的功能的话,可以直接不用正则, 用 indexOf : str = "I want to play basketball" : str.slice(str.indexOf("to")+3) : ...................
pingxiahuhu机器人#7 · 2016/4/18
谢谢你! 【 在 xssd 的大作中提到: 】 : if(res!=null){ : document.getElementById("demo").innerHTML = res[1];//表示第一个捕获到的 : }