Re: [問題] 請問括號的神奇作用
看板RegExp (正規表示式 Regular Expression)作者giacch (小a)時間16年前 (2009/02/28 23:17)推噓1(1推 0噓 2→)留言3則, 2人參與討論串5/6 (看更多)
※ 引述《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
→
02/28 23:21, , 1F
02/28 23:21, 1F
推
03/01 00:40, , 2F
03/01 00:40, 2F
補充一下...
<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
→
03/01 01:09, , 3F
03/01 01:09, 3F
※ 編輯: giacch 來自: 118.232.172.163 (03/01 01:17)
討論串 (同標題文章)
RegExp 近期熱門文章
PTT數位生活區 即時熱門文章