Một số instance method của kiểu dữ liệu chuỗi ở trong JS:
concat
-
Cú pháp:
concat(str1, str2, str3, ...) -
Dùng khi: cần nối chuỗi.
-
Ví dụ:
let greeting = "Hello!" let asking = " How are you?" let newString = greeting.concat(asking) console.log(newString) // Hello! How are you?
indexOf And lastIndexOf
-
Cú pháp:
indexOf(str)vàlastIndexOf(str). -
Dùng khi:
indexOf(str): cần tìm kiếm vị trí của chuỗistrtrong chuỗi khác. Chiều tìm kiếm từ trái sang phải.lastIndexOf(str): tương tự vớiindexOfnhưng có chiều tìm kiếm ngược lại.
-
Ví dụ:
let greeting = "Hello!" let subStr = "Hell" let foundPos = greeting.indexOf(subStr) console.log(foundPos) // 0
charAt And charCodeAt
-
Cú pháp:
charAt(index)vàcharCodeAt(index) -
Dùng khi:
charAt(index): cần lấy ra giá trị của một ký tự tại vị tríindextrong chuỗi.charCodeAt(index): cần lấy ra giá trị ASCII của ký tự tại vị tríindextrong chuỗi.
-
Ví dụ:
let greeting = "Hello world!" console.log(greeting.charAt(9)) // l console.log(greeting.charAt(0)) // H console.log(greeting.charAt(greeting.length - 1)) // !
replace
-
Cú pháp:
replace(search, replacement) -
Dùng khi: cần thay thế chuỗi
searchtrong chuỗi gốc bằng chuỗireplacement. -
Ví dụ:
let greeting = "Hello world!" let goodbye = greeting.replace("Hello", "Goodbye") console.log(goodbye) // Hello-world!
Info
Chuỗi con cần tìm có thể là một biểu thức chính quy (Regular Expression).
split
-
Cú pháp:
split(separator) -
Dùng khi: cần tách một chuỗi ra thành nhiều chuỗi con dựa trên một hoặc nhiều ký tự phân cách
separatorcho trước. Nếu không truyền vào đối số, mảng trả về sẽ chứa một phần tử và phần tử đó cũng chính là chuỗi ban đầu. -
Ví dụ:
let techs = "ReactJS, ReduxJS, NodeJS, ExpressJS, NextJS" console.log(techs.split(", ")) // ["ReactJS", "ReduxJS", "NodeJS", "ExpressJS", "NextJS"] console.log(techs.split()) // ["ReactJS, ReduxJS, NodeJS, ExpressJS, NextJS"]
substring
-
Cú pháp:
substring(startIndex, endIndex) -
Dùng khi: cần lấy ra một chuỗi con dựa trên chỉ số bắt đầu và chỉ số kết thúc. Ký tự ở vị trí
endIndexsẽ không được lấy. -
Ví dụ:
let greeting = "Hello world!" console.log(greeting.substring(2, 8)) // llo wo
trim
-
Cú pháp:
trim() -
Dùng khi: cần xóa đi những khoảng trắng ở hai đầu của chuỗi.
-
Ví dụ:
let greeting = " Hello world! " console.log(greeting.trim()) // Hello world!