Khi nối chuỗi với +, nếu chuỗi đầu đã kết thúc bằng khoảng trắng, không cần thêm " " thủ công.
Chuỗi đầu có space cuối
<script>
function noiChuoi(str1, str2) {
return str1 + str2; // Không cần + " "
}
document.write(noiChuoi("Tutorix is the best ", "e-learning platform"));
// "Tutorix is the best e-learning platform"
</script>
Chuỗi đầu KHÔNG có space cuối
<script>
function noiChuoiCoSpace(str1, str2) {
return str1 + " " + str2; // Phải thêm space
}
document.write(noiChuoiCoSpace("Tutorix is the best", "e-learning platform"));
// "Tutorix is the best e-learning platform"
</script>
Cách an toàn: Tự động xử lý
function noiAnToan(str1, str2) {
const s1 = String(str1).trimEnd();
const s2 = String(str2).trimStart();
return s1 + (s1 && s2 ? ' ' : '') + s2;
}
// Test
noiAnToan("Hello ", "world"); // "Hello world"
noiAnToan("Hello", " world"); // "Hello world"
noiAnToan("Hello", "world"); // "Hello world"
noiAnToan("Hello ", " world"); // "Hello world" (không double space)
Template Literal (ES6) — Tự nhiên hơn
const greeting = `${str1}${str2}`; // Không auto space
const greeting2 = `${str1.trimEnd()} ${str2.trimStart()}`; // An toàn
Tóm tắt
| Trường hợp | Code | Kết quả |
|---|---|---|
| str1 có space cuối | str1 + str2 | Đúng (1 space) |
| str1 không space, str2 có space đầu | str1 + str2 | Đúng (1 space) |
| Cả hai đều không space | str1 + " " + str2 | Đúng |
| Cả hai đều có space | str1 + str2 | Sai (2 space) → dùng trim |