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

ใช้ Regex ดึงค่าระหว่างวงเล็บเหลี่ยม [] ใน JavaScript

ดึงข้อความภายในวงเล็บเหลี่ยมด้วย Lookahead/Lookbehind

ใช้ Regular Expression พร้อม match() เพื่อจับค่าระหว่าง [ และ ] โดยไม่รวมวงเล็บ

ตัวอย่างโค้ด

var regularExpression = /(?<=\[).*?(?=\])/g;
var getTheValueWithIndex = "[John Smith][David Miller]".match(regularExpression);

console.log("ค่าแรกโดยไม่มีวงเล็บ = " + getTheValueWithIndex[0]); // John Smith
console.log("ค่าที่สองโดยไม่มีวงเล็บ = " + getTheValueWithIndex[1]); // David Miller

วิธีรัน

node fileName.js

ผลลัพธ์

The first value without bracket = John Smith
The second value without bracket = David Miller

คำอธิบาย Regex

  • (?<=\[): Positive Lookbehind - ต้องมี [ อยู่ก่อนหน้า
  • .*?: จับข้อความทุกตัวอักษร (non-greedy)
  • (?=\]): Positive Lookahead - ต้องมี ] อยู่ถัดไป
  • /g: Global flag - หาทุกครั้งที่เจอในสตริง

รองรับเบราว์เซอร์เก่า (ไม่มี Lookbehind)

var regex = /\[([^\]]+)\]/g;
var str = "[John Smith][David Miller]";
var matches = [];
var match;
while ((match = regex.exec(str)) !== null) {
  matches.push(match[1]); // กลุ่มที่ 1 คือข้อมูลภายในวงเล็บ
}
console.log(matches); // ["John Smith", "David Miller"]