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

Extract ข้อความระหว่าง Double Quotes ด้วย JavaScript

เรียนรู้ extract ข้อความระหว่าง double quotes จาก string ด้วย JavaScript

Quotes มักห่อด้วย double quotes (" ") ใช้ match() + RegEx

Text block มี 1 quoted sentence assign ให้ textWithQuote:

const textWithQuote = 'One of my favorite quotes is "First we make our habits, then our habits make us". This quote is sometimes attributed to John Dryden, or other authors.';

Attach match() argument ค่อนข้างซับซ้อน:

const extractQuote = textWithQuote
  .match(/(?:"[^"]*"|^[^"]*$)/)[0]
  .replace(/"/g, "");

Print result:

console.log(extractQuote); // "First we make our habits, then our habits make us"

เหตุผล [0]: ไม่ใส่ string จะ duplicate ใช้ [0] ระบุว่าเอาแค่ result แรก

เหตุผล replace(): ไม่ใส่ จะได้ quotes เหลือ (เพราะ return quoted text ใน string ที่มี quotes อยู่แล้ว)

Alternative Method: split()

const textWithQuote = 'One of my favorite quotes is "First we make our habits, then our habits make us". This quote is sometimes attributed to John Dryden, or other authors.';
console.log(textWithQuote.split('"')[1]); // "First we make our habits, then our habits make us"

ต้องระบุ [1] เพราะ [0] จะได้ One of my favorite quotes is

[2] จะได้ข้อความหลัง double quote ที่ 2

ยังไม่แน่ใจว่าเมื่อไหร่ควรใช้วิธีไหน pros/cons อะไร เพราะเพิ่งเริ่มดive deep regex