Check if a string has white space

前端 未结 7 1579
青春惊慌失措
青春惊慌失措 2020-11-30 19:41

I\'m trying to check if a string has white space. I found this function but it doesn\'t seem to be working:

function hasWhiteSpace(s) 
{
            


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 20:06

    With additions to the language it is much easier, plus you can take advantage of early return:

    // Use includes method on string
    function hasWhiteSpace(s) {
      const whitespaceChars = [' ', '\t', '\n'];
      return whitespaceChars.some(char => s.includes(char));
    }
    
    // Use character comparison
    function hasWhiteSpace(s) {
      const whitespaceChars = [' ', '\t', '\n'];
      return Array.from(s).some(char => whitespaceChars.includes(char));
    }
    
    const withSpace = "Hello World!";
    const noSpace = "HelloWorld!";
    
    console.log(hasWhiteSpace(withSpace));
    console.log(hasWhiteSpace(noSpace));
    
    console.log(hasWhiteSpace2(withSpace));
    console.log(hasWhiteSpace2(noSpace));
    

    I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

提交回复
热议问题