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

วิธีลบข้อความออกจาก String ใน JavaScript

ลบข้อความจาก string ใน JavaScript ได้ 2 วิธี: substring และ replace

Substring

JS string class มี substring method extract substring จาก string ให้ใช้ลบข้อความจากปลายหนึ่งหรือทั้งสองได้

Syntax

str.substr(start[, length])

ตัวอย่าง

let a = 'Hello world' console.log(a.substr(0, 5)) console.log(a.substr(6)) console.log(a.substr(4, 3))

ผลลัพธ์

Hello world o w

Replace

JS string class มี replace method แทนที่ substring ด้วย empty string ใช้ลบข้อความจากปลายหนึ่งหรือทั้งสองได้

Syntax

str.replace(old, new)

ตัวอย่าง

let a = 'Hello world' console.log(a.replace(" world", "")) console.log(a.replace("Hello ", "")) console.log(a.replace("o w", ""))

ผลลัพธ์

Hello world hellorld