Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

บทบาทของคุณสมบัติ global ใน JavaScript RegExp

คุณสมบัติ global เป็นคุณสมบัติบูลีนแบบอ่านอย่างเดียว (read-only) ของออบเจ็กต์ RegExp ระบุว่า regular expression นั้นทำการจับคู่แบบทั่วทั้งสตริง (global matching) หรือไม่ คือว่าถูกสร้างด้วยแอตทริบิวต์ "g" หรือไม่

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อเรียนรู้การทำงานกับคุณสมบัติ global ของ RegExp:

<html>
  <head>
    <title>JavaScript RegExp global Property</title>
  </head>
  <body>
    <script>
      var re = new RegExp( "string" );
      if ( re.global ){
        document.write("Test1 - Global property is set");
      } else {
        document.write("Test1 - Global property is not set");
      }
      re = new RegExp( "string", "g" );
      if ( re.global ){
        document.write("<br />Test2 - Global property is set");
      } else {
        document.write("<br />Test2 - Global property is not set");
      }
    </script>
  </body>
</html>

Test 1: ไม่มีฟลาก g → global = false Test 2: มีฟลาก g → global = true คุณสมบัตินี้เกี่ยวข้องกับ lastIndex ซึ่งทำงานก็ต่อเมื่อ global = true เท่านั้น