Dùng indexOf(' ') tìm dấu cách. Trả về >= 0 nếu tìm thấy. Hoặc dùng includes(' ') (ES2016).
Ví dụ
function hasWhitespace(str) {
return str.indexOf(' ') >= 0;
// Hoặc: return str.includes(' ');
}
var test = "MyNameis John";
if (hasWhitespace(test)) {
console.log("Chuỗi CÓ khoảng trắng");
} else {
console.log("Chuỗi KHÔNG có khoảng trắng");
}
Cách chạy
node demo.js
Kết quả
Chuỗi CÓ khoảng trắng
Mở rộng - kiểm tra mọi whitespace (tab, newline):
const hasAnyWhitespace = str => /\s/.test(str);
// Hoặc
const hasAnyWhitespace = str => [...str].some(c => c.trim() === '');