【问题标题】:How to make a field that recognizes letters and numbers with Javascript?如何使用Javascript创建一个识别字母和数字的字段?
【发布时间】:2020-07-24 16:19:20
【问题描述】:

如何制作一个<imput> 字段,可以识别字母和数字并忽略空格或大写拼写?

以下是我到目前为止所做的,我的目标是当9 H 6 U 8 f 被写入字段时feedback"right",即使字符之间没有空格或者即使字母不是大写。

function F1() {

  antw = parseFloat(document.getElementById("userAnswer").text);
  feedBack = document.getElementById("feedBack");
  ant = document.getElementById("answer").textContent;
  {
    if (antw == ant) {
      feedBack.textContent = "Right";

    } else {
      feedBack.textContent = "Wrong";
    }
  }
}
<button onclick="F1()">check</button>
<input id="userAnswer" type=text>
<p id="feedBack"> </p>
Write:<label id="answer"> 9 H 6 U 8 f</label>

【问题讨论】:

  • 所有&lt;input type='text'&gt; 都会识别字母数字、空格,并且不区分大小写。

标签: javascript html


【解决方案1】:

您需要使用删除两个值中的所有空格

.replace(/\s+/g, '')

然后将两者都转换为小写使用

.toLowerCase()

然后您可以独立于大小写和空格来比较它们:

function F1() {
  feedBack = document.getElementById("feedBack");
  antw = document.getElementById("userAnswer").value.replace(/\s+/g, '').toLowerCase();
  ant = document.getElementById("answer").textContent.replace(/\s+/g, '').toLowerCase();
  {
    if (antw == ant) {
      feedBack.textContent = "Right";

    } else {
      feedBack.textContent = "Wrong";
    }
  }
}
<button onclick="F1()">check</button>
<input id="userAnswer" type="text">
<p id="feedBack"> </p>
Write:<label id="answer"> 9 H 6 U 8 f</label>

请注意,要获取input 元素的内容,请使用.value,而不是.text

【讨论】:

    【解决方案2】:

    一种选择是在判断正确或错误之前使用正则表达式从 javascript 函数中的字符串中去除空格:

    str = str.replace(/\s/g, '');
    

    以上代码将删除空格。有关可运行的 sn-p,请参阅 this answer

    关于大小写,使用 javascript toLowerCase 函数将任何大写字母去大写 即使字符串中有数字,toLowerCase() 函数也可以工作;它只会影响字母。所以 9 H R 会变成 9 h r 等等。

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      比较两个字符串的最佳方法是将两者都转换为小写并删除所有空格。有几种方法(和代码中的位置)可以做到这一点,但我建议创建第二个函数来处理字符串。这样,您的函数每个只做一件事。

      const trimAndLowerCase = (input) => {
        return input.replace(/\s+/g, '').toLowerCase();
      }
      
      const f1 = () => {
        const input = document.getElementById('userAnswer').value;
        const answer = document.getElementById('answer').textContent;
        const feedback = document.getElementById('feedBack');
      
        if (trimAndLowerCase(input) === trimAndLowerCase(answer)) {
          feedback.textContent = 'Right';
        } else {
          feedback.textContent = 'Wrong';
        }
      }
      

      编辑:如果您想知道,上面的代码使用arrow function expression 来创建函数。如果您需要 IE 兼容性,则必须使用旧的 function f1() 语法。

      【讨论】:

        【解决方案4】:

        您可以在比较它们之前简化字符串。详情在demo中注释。

        // Reference the <form>
        const ver = document.forms.verify;
        
        // Regiter the <form> to the "submit" event
        ver.onsubmit = matchText;
        
        // Event handler function passes the event Object
        function matchText(event) {
        
          /* 
          Stop default behavior of <form> when "submit" event is   
          triggered. Default behavior is that <form> values are 
          sent to a server and then <form> is reloaded.
          */
          event.preventDefault();
          
          // Collect all form fields into an array-like object
          const field = this.elements;
          
          /*
          Get the text of <output id='captcha'> and call
          simpleText() (see the end of code) to remove spaces and
          change to lower case
          */
          let compareTo = simpleText(field.captcha.textContent);
          
          // Likewise for the value of <input id='data'>
          let userInput = simpleText(field.data.value);
          
          /*
          if the two strings are exactly the same, render the HTML
          of <output id='result'> as <i>RIGHT!</i> otherwise set it
          to <b>WRONG!</b>
          */
          let result = compareTo === userInput ? `<i>RIGHT!</i>` : `<b>WRONG!</b>`;
          field.result.innerHTML = result;
        }
        
        // Utility function passes thru a string
        function simpleText(string) {
        
          /* 
          split() the string up by removing all spaces then convert
          the string into an array of letters. join() the letters
          together back into a string.
          */
          let text = string.split(' ').join('');
          
          // return string to lower case
          return text.toLowerCase();
        }
        input, button, output {display: inline-block; font: 400 3vw/1.5 Verdana}
        #data {width: 10ch}
        #captcha {color: goldenrod}
        #result i {color: lime; font-weight: 900}
        #result b {color: tomato}
        <form id='verify'>
          <input id='data' type='text'><input type='submit' value='VERIFY'><hr>
          <output id='captcha'>9 H 6 U 8 f</output>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <output id='result'></output>
        </form>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-30
          相关资源
          最近更新 更多