作者giacch (小a)
看板RegExp
标题Re: [问题] 请问括号的神奇作用
时间Sat Feb 28 23:17:58 2009
※ 引述《grence (多想两分钟 = =")》之铭言:
: 弄成简单的例子....
: <script type='text/javascript'>
: var htmlText="<body> ... <body> .... </body> .. </body>";
: alert(/<body>/g.exec(htmlText));//<body>
: alert(/(<body>)/g.exec(htmlText));//<body>,<body>
: </script>
: IE7 跟 FireFox的结果一样,我也很好奇这两个差在哪里…
原以为 因为有两个body 所以有加()的传回两个body 但看来不是...
而且传回的都是第一个body
<script type='text/javascript'>
var htmlText="<bodya> ... <bodyb> .... </body> .. </body>";
alert(/(<body.?>)/g.exec(htmlText)); //<bodya>,<bodya>
alert(/<body.?>/g.exec(htmlText)); //<bodya>
</script>
就算只给一个body 有加()的还是会传回 <body>,<body>
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.232.172.163
1F:→ giacch: Opera 02/28 23:21
2F:推 xrancyma:感觉很像是BUG…该不会 IE 和 FF 的 BUG 都一样吧? 03/01 00:40
补充一下...
<script type='text/javascript'>
var htmlText="<bodya> .. <bodyb> .... <bodyc>";
alert( "A: " + htmlText.match(/(<body.?>)/g) ); // A: <bodya>,<bodyb>,<bodyc>
alert( "B: " + htmlText.match(/(<body.?>)/g).length ); // B: 3
alert( "C: " + htmlText.match(/(<body.?>)/g)[0] ); // C: <bodya>
alert( "D: " + htmlText.match(/(<body.?>)/g)[1] ); // D: <bodyb>
alert( "E: " + htmlText.match(/(<body.?>)/g)[2] ); // E: <bodyc>
alert( "F: " + htmlText.match(/(<body.?>)/g)[3] ); // F: undefined
</script>
以下取自
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
exec() Search a string for a specified value. Returns the found
value and remembers the position
match() Search a string for a specified value. Returns an array
of the found value(s)
( ) Finds the group of characters inside the parentheses
and stores the matched string
3F:→ giacch: 爆... XD 03/01 01:09
※ 编辑: giacch 来自: 118.232.172.163 (03/01 01:17)