【问题标题】:How to check if the text is missing a certain character?如何检查文本是否缺少某个字符?
【发布时间】:2021-01-26 01:46:29
【问题描述】:

我正在处理的任务有一个 div,您需要在其中输入您的电子邮件。这是一个简单的任务,只需要检查电子邮件是否缺少@和句号,然后显示某些文本,没什么太复杂的。但是,我尝试使用 include() 函数,Chrome 控制台显示错误,指出 varname.includes() 它不是函数。

这是我的 HTML 代码的一部分,在使用 onlick 后应该执行 JavaScript:

<div class="warning"> </div>

<div class="email">
  <input class="mail" type="email" name="mail" placeholder="your email">
  <input class="send" type="submit" name="send" value="SEND" onclick="checkEmail()">
</div>

基本上,JavaScript 代码需要做的是:

  1. 如果缺少@,请在警告 div 中写上“缺少@”。
  2. 如果缺少 .,请填写“missing .”。在警告 div 中。
  3. 如果缺少 @ 和 .,请填写“您的电子邮件地址不正确!”在警告 div 中。
  4. 如果电子邮件同时满足这两个条件,它会发出警报,提示“您已加入!”

正如我所提到的,我尝试在 if 中使用 include(),但它不起作用,我不知道还有什么可以在这里起作用。我知道如何发出警报或编写文本等基础知识,我只是不知道如何让代码检查字符是否存在或丢失。对此的任何帮助将不胜感激!

【问题讨论】:

  • 它应该与string.includes("@") && string.includes(".") 一起使用,如果字符串中的参数中有字符,则返回true。确保在字符串上使用此方法。
  • 您可以在输入元素中使用pattern 属性。它们使用正则表达式。

标签: javascript


【解决方案1】:
const toCheckFor = ["@", "."] // Array of all characters to check for
const text = "whatever you want" // text you want to check in
let flag = true // flipped to false if one character in the array not found

toCheckFor.forEach(e => {
   flag &= text.includes(e)
})

如果text 包含toCheckFor 中的所有字符,则标志将为真。

【讨论】:

    【解决方案2】:

    这是基于您的帖子的示例...

    const mail = document.querySelector('input[name="mail"]');  // cache for later use
    const warning = document.querySelector('.warning');         // cache for later use
    
    function checkEmail() {
      
      const error = {};
      const text = mail.value;
      
      if (!text.includes('@') && !text.includes('.')) {
        
        warning.textContent = 'Your email address is not correct!';
        return; // end here
      }
    
    /*  
      this is a shorthand
      you can also write 
      if (!text.includes('@')) {
        error.push('missing @');
      }
    */
      !text.includes('@') && error.push('missing @');
      !text.includes('.') && error.push('missing .');
    
      if (!error[0]) {            // there are some errors
        warning.textContent = error.join(' & ');
      }
      else {                      // no error
        warning.textContent = "You are in!";
      }
    } 
    

    【讨论】:

      【解决方案3】:

      我建议您最好通过以下函数对输入的电子邮件地址使用正则表达式检查:

      function validateEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-31
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 2019-12-27
        • 1970-01-01
        • 2011-08-10
        相关资源
        最近更新 更多