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

Các phương thức String phổ biến trong JavaScript

String object bao bọc primitive string, cung cấp nhiều helper method. JS auto-coerce giữa primitive và object nên gọi method trực tiếp trên string literal.

Danh sách method hay dùng

Method Mô tả
concat()Nối chuỗi, trả chuỗi mới
indexOf()Vị trí đầu tiên tìm thấy, -1 nếu không
lastIndexOf()Vị trí cuối cùng tìm thấy
match()Match regex, trả array hoặc null
replace()Thay thế match regex/substring
search()Tìm regex, trả index đầu tiên
slice()Cắt substring (hỗ trợ index âm)
split()Tách chuỗi thành array theo separator
substr()(Deprecated) Cắt từ vị trí, độ dài cho trước
substring()Cắt giữa 2 index (không hỗ trợ âm)
toLowerCase()Chuyển lowercase
toUpperCase()Chuyển uppercase
valueOf()Trả primitive value
trim()Xóa whitespace đầu/cuối (ES5+)
startsWith()/endsWith()Kiểm tra prefix/suffix (ES6+)
includes()Kiểm tra chứa substring (ES6+)

Ví dụ nhanh

let a = "Hello World!";
console.log(a.concat(" test"));      // "Hello World! test"
console.log(a.indexOf("l"));         // 2
console.log(a.lastIndexOf("l"));     // 9
console.log(a.replace("Hello", "Hi")); // "Hi World!"
console.log(a.substr(3, 7));         // "lo Worl"
console.log(a.toUpperCase());        // "HELLO WORLD!"