如果空字符串 [eg: ' '] 或字符串仅包含空格 [eg: ' '],我们如何单独检查 true/false?

How can we check seperately true/false if empty string [eg: ' '] or string contain only white spaces [eg: ' ']?

嗨,团队,我是新手,javascript。我正在处理一些验证部分。只有当它是空字符串或非空字符串时我才需要输入,但它不应该只是空格..?我如何检查该条件?

var element='' // this should take 
var element='       ' // this shouldnot (bcz contain only empty space) 
var element='Hai how are you'  // this should take
var element='  jji       hooy      ' // this should also take

有人可以帮助我使用 trim() 但如果可以,它无法识别“”和“”

任何其他解决方案

您可以使用正则表达式来匹配包含空格的字符串。

!/^\s+$/.test('');    // true
!/^\s+$/.test('   '); // false
!/^\s+$/.test('Hai how are you');        // true
!/^\s+$/.test('  jji       hooy      '); // true
  • !表示“不是”
  • ^ 表示“字符串的开头”
  • $ 表示“字符串结尾”
  • \s+ 表示‘空格,一次或多次’

您可以这样验证它:

validate(element) {
    return element.length && element.trim().length;
}

您可以使用以下内容:

if(str.length && str.trim() === ""){
    return false
  }else{
    return true
  }

如果输入值没有长度,设置状态。如果输入值 长度,当你 trim 它仍然有长度时,设置值。否则不要设置输入状态。

const { useEffect, useState } = React;

function Example() {

  const [ input, setInput ] = useState('');

  function handleChange(e) {

    // Get the value, and the length of the value
    const { value, value: { length } } = e.target;

    // Check the condition, set the state
    if (!length || (length && value.trim().length !== 0)) {
      setInput(value);
    }
  }

  // Log the updated state
  useEffect(() => console.log(`Current state: ${input}`), [input]);

  return <input onChange={handleChange} />;

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>