Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa text khỏi string trong JavaScript

2 cách chính: substring/slice (cắt theo index) và replace (thay thế pattern).

1. substring / slice (cắt vị trí)

str.substring(start[, end]) // end không inclusive
str.slice(start[, end])     // hỗ trợ index âm
let a = 'Hello world';
console.log(a.substring(0, 5)); // "Hello"
console.log(a.substring(6));    // "world"
console.log(a.slice(4, 7));     // "o w"

2. replace (thay thế pattern)

str.replace(searchValue, replaceValue)
let a = 'Hello world';
console.log(a.replace(" world", ""));   // "Hello"
console.log(a.replace("Hello ", ""));   // "world"
console.log(a.replace("o w", ""));      // "Hellorld"

// Regex replace all
console.log("hello world".replace(/l/g, "")); // "heo word"

Chọn cách nào?

  • Biết index chính xác → slice/substring.
  • Biết pattern/chuỗi con → replace (hỗ trợ regex, replace all với flag g).