久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長(zhǎng)資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      Javascript中使用exec進(jìn)行正則表達(dá)式全局匹配時(shí)的注意事項(xiàng)

      本文就是介紹在使用 Javascript 中使用 exec 進(jìn)行正則表達(dá)式全局匹配時(shí)的注意事項(xiàng)。
      先看一下常見的用法:

      復(fù)制代碼 代碼如下:
      <script type=”text/javascript”>
      var pattern = /http://([^/s]+)/;
      alert(pattern.exec(‘http://www.codebit.cn’)); // http://www.codebit.cn,www.codebit.cn
      alert(pattern.exec(‘http://YITU.org’)); // http://YITU.org,YITU.org
      // 也可以直接寫成 /http://([^/]+)/.exec(‘http://www.codebit.cn’);
      </script>

      接下來看一下全局模式下的詭異事件:

      復(fù)制代碼 代碼如下:
      <script type=”text/javascript”>
      var pattern = /http://([^/s]+)/g; // 使用了 g 修飾符
      alert(pattern.exec(‘http://www.codebit.cn’)); // http://www.codebit.cn,www.codebit.cn
      alert(pattern.exec(‘http://YITU.org’)); // 并沒有返回期望的 http://YITU.org,YITU.org ,而是返回了 null
      </script>

      第二個(gè)語句并沒有返回期望的結(jié)果,而是返回了 null ,這是因?yàn)椋?
      在全局模式下,當(dāng) exec() 找到了與表達(dá)式相匹配的文本時(shí),在匹配后,它將把正則表達(dá)式對(duì)象的 lastIndex 屬性設(shè)置為匹配文本的最后一個(gè)字符的下一個(gè)位置。這就是說,您可以通過反復(fù)調(diào)用 exec() 方法來遍歷字符串中的所有匹配文本。當(dāng) exec() 再也找不到匹配的文本時(shí),它將返回 null,并把 lastIndex 屬性重置為 0。
      下面是正常的全局模式下的匹配方式:

      復(fù)制代碼 代碼如下:
      <script type=”text/javascript”>
      var pattern = /http://([^/s]+)/g;
      var str = “CodeBit.cn : http://www.codebit.cn | YITU.org : http://YITU.org”;
      var result;
      while ((result = pattern.exec(str)) != null) {
      alert(“Result : ” + result + ” LastIndex : ” + pattern.lastIndex);
      }
      //Result : http://www.codebit.cn,www.codebit.cn LastIndex : 34
      //Result : http://YITU.org,YITU.org LastIndex : 67
      </script>

      從上面的代碼我們可以看到,之所以出現(xiàn)第二段代碼中的問題,影響因素是 lastIndex ,所以我們可以通過將 lastIndex 手動(dòng)置 0 的方式來解決這個(gè)問題。

      復(fù)制代碼 代碼如下:
      <script type=”text/javascript”>
      var pattern = /http://([^/s]+)/g; // 使用了 g 修飾符
      alert(pattern.exec(‘http://www.codebit.cn’)); // http://www.codebit.cn,www.codebit.cn
      pattern.lastIndex = 0;
      alert(pattern.exec(‘http://YITU.org’)); // http://YITU.org,YITU.org
      </script>

      總結(jié):
      在全局模式下,如果在一個(gè)字符串中完成了一次模式匹配之后要開始檢索新的字符串,就必須手動(dòng)地把 lastIndex 屬性重置為 0。

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)