Text.Replace ใช้สำหรับแทนที่ทุกส่วนของข้อความเก่าในข้อความหลักด้วยข้อความใหม่ เป็น Case Sensitive และแทนที่ทีละครั้งที่เจอในข้อความทั้งหมด
=Text.Replace(text as nullable text, old as text, new as text) as nullable text
=Text.Replace(text as nullable text, old as text, new as text) as nullable text
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| text | text | Yes | ข้อความต้นฉบับที่ต้องการค้นหาและแทนที่ | |
| old | text | Yes | ข้อความย่อยที่ต้องการค้นหาและแทนที่ | |
| new | text | Yes | ข้อความใหม่ที่จะแทนที่ |
เปลี่ยนรหัสสินค้าจาก "PROD-" เป็น "ITEM-"
แทนที่คำผิด หรือสัญลักษณ์พิเศษ เช่น "#N/A" ด้วยค่าว่าง
แทนที่ช่องว่างในชื่อไฟล์ด้วยเครื่องหมายขีดกลาง (-) สำหรับ URL
Text.Replace("apple", "pp", "rr")= Text.Replace("apple", "pp", "rr")
arrle
Text.Replace("banana", "a", "o")= Text.Replace("banana", "a", "o")
bonono
let ProductCode = "PROD-2024-001", Clean = Text.Replace(ProductCode, "-", "") in Cleanlet
ProductCode = "PROD-2024-001",
Clean = Text.Replace(ProductCode, "-", "")
in
Clean
PROD2024001
let Encoded = "Hello%20World%20from%20Power%20Query", Decoded = Text.Replace(Encoded, "%20", " ") in Decodedlet
Encoded = "Hello%20World%20from%20Power%20Query",
Decoded = Text.Replace(Encoded, "%20", " ")
in
Decoded
Hello World from Power Query
ใช่ครับ เป็น Case Sensitive สมบูรณ์ ตัวอย่างเช่น Text.Replace(“Apple”, “apple”, “Orange”) จะไม่แทนที่อะไรเลย ถ้าต้องการแทนที่ไม่สนใจ Case สามารถใช้ Text.Upper(text) หรือ Text.Lower(text) ทั้งคำค้นหาและข้อความเดิมก่อน
Text.Replace จะแทนที่ทุกครั้งที่พบ ถ้าต้องแทนที่แค่ครั้งแรก ต้องใช้วิธีอื่น เช่น สร้าง custom formula ด้วย Text.RemoveRange ร่วมกับ Text.Insert และ Text.PositionOf เพื่อหาตำแหน่งแรกที่พบ
จะได้ null กลับมา ถ้าต้องการหลีกเลี่ยงสถานการณ์นี้ ตรวจสอบ null ก่อน เช่น if text null then Text.Replace(text, old, new) else “”
Text.Replace ทำหน้าที่ค้นหาข้อความย่อย (substring) ที่ระบุจากข้อความหลัก แล้วแทนที่ด้วยข้อความใหม่ทีละครั้งที่เจอในข้อความทั้งหมด
ส่วนตัวมักใช้ Text.Replace เพื่อเช็ดทำความสะอาด (clean up) ข้อมูลที่ไม่สอดคล้องกัน เช่น ลบ suffix, prefix หรือแทนที่เครื่องหมายพิเศษ 😎 สิ่งที่ต้องระวัง คือ Text.Replace เป็น Case Sensitive ถ้าต้องการแทนที่ไม่สนใจ Case ต้องใช้ Text.Upper หรือ Text.Lower ก่อน หรือใช้ฟังก์ชันที่มี Comparer.OrdinalIgnoreCase