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

การใช้งาน split() ใน JavaScript

เมธอด split([separator, [limit]]) แยก String object เป็น array ของ strings โดยแยกสตริงเป็น substrings ใช้ separator string ที่ระบุกำหนดจุดแยก

ตัวอย่างการใช้ split

let a = "hello,hi,bonjour,namaste"; let greetings = a.split(','); console.log(greetings)

ผลลัพธ์

[ 'hello', 'hi', 'bonjour', 'namaste' ]

สังเกตว่า commas ถูกลบไป separator ใดก็ตามที่ให้จะถูกลบ

ถ้า separator เป็น empty string str จะกลายเป็น array ที่มี element ตัวละตัวอักษร

ตัวอย่าง

let a = "hello"; console.log(a.split(""))

ผลลัพธ์

[ 'h', 'e', 'l', 'l', 'o' ]

ถ้าไม่ให้ separator จะคืน string ตัวเดิม

ตัวอย่าง

let a = "hello world" console.log(a.split())

ผลลัพธ์

hello world