Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ตรวจสอบว่าสตริงมีช่องว่างหรือไม่ใน JavaScript

ใช้ indexOf(' ') หาช่องว่าง คืนค่า >= 0 แปลว่ามีช่องว่าง

ตัวอย่างโค้ด

function stringHasTheWhiteSpaceOrNot(value) {
    return value.indexOf(' ') >= 0;
}

var whiteSpace = stringHasTheWhiteSpaceOrNot("MyNameis John");

if (whiteSpace == true) {
    console.log("The string has whitespace");
} else {
    console.log("The string does not have whitespace");
}

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo108.js)

ผลลัพธ์

The string has whitespace

ทางเลือก: ใช้ Regex /\s/.test(str) ครอบคลุม Tab, Newline ด้วย