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

แทนที่คอมมาล่าสุดในสตริงด้วย JavaScript Regex

Regex แทนที่คอมมาตัวสุดท้าย (Lookahead Assertion)

ใช้ replace() กับ regex /,(?=[^,]*$)/ จับคอมมาที่ตามด้วย non-comma จนจบสตริง

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


const makingRegularExpression = /,(?=[^,]*$)/;

function replaceComma(values) {
  console.log(values, " ==== replaced by JavaScript ==== ", 
    values.replace(makingRegularExpression, " JavaScript"));
}

replaceComma("My Favorite subject is,");
replaceComma("My Favorite subject is, and teacher name is Adam Smith");
replaceComma("My Favorite subject is, and got the marks 89");

วิธีรัน

node fileName.js

ผลลัพธ์


My Favorite subject is, ==== replaced by JavaScript ==== My Favorite subject is JavaScript
My Favorite subject is, and teacher name is Adam Smith ==== replaced by JavaScript ==== My Favorite subject is JavaScript and teacher name is Adam Smith
My Favorite subject is, and got the marks 89 ==== replaced by JavaScript ==== My Favorite subject is JavaScript and got the marks 89

คำอธิบาย Regex

  • , - จับคอมมา
  • (?=[^,]*$) - Positive Lookahead: ต้องตามด้วย [^,]* (ไม่ใช่คอมมา 0 ตัวขึ้นไป) จนถึง $ (จบสตริง)
  • หมายถึง: คอมมาตัวสุดท้ายของสตริง

กรณีต้องการแทนที่คอมมาทั้งหมด


str.replace(/,/g, ' JavaScript'); // global flag

กรณีแทนที่คอมมาแรก


str.replace(/,/, ' JavaScript'); // ไม่มี g flag