我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。

注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。

我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?


当前回答

检查字符串(单词/句子…)是否包含特定的单词/字符

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 

其他回答

例如,如果要从DOM读取数据,例如p或h1标记,则需要使用两个原生JavaScript函数,这非常简单,但仅限于es6,至少对于我将要提供的解决方案是这样。我将搜索DOM中的所有p标签,如果文本包含“T”,整个段落将被删除。我希望这个小例子能帮助到一些人!

HTML

<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>

JS

let paras = document.querySelectorAll('p');

paras.forEach(p => {
  if(p.textContent.includes('T')){
       p.remove();
    } 
});

检查字符串是否为字母数字或字母数字+一些允许的字符

最快的字母数字方法可能是如上所述:在Javascript中字母数字检查的最佳方法,因为它直接操作数字范围。

然后,为了允许其他一些额外的字符,我们可以把它们放在一个Set中进行快速查找。

我相信这个实现将正确地处理代理对。

#!/usr/bin/env node

const assert = require('assert');

const char_is_alphanumeric = function(c) {
  let code = c.codePointAt(0);
  return (
    // 0-9
    (code > 47 && code < 58) ||
    // A-Z
    (code > 64 && code < 91) ||
    // a-z
    (code > 96 && code < 123)
  )
}

const is_alphanumeric = function (str) {
  for (let c of str) {
    if (!char_is_alphanumeric(c)) {
      return false;
    }
  }
  return true;
};

// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
  for (let c of str) {
    if (
      !char_is_alphanumeric(c) &&
      !is_almost_alphanumeric.almost_chars.has(c)
    ) {
      return false;
    }
  }
  return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);

assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('你好'));

assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('你好'));

GitHub上游。

在Node.js v10.15.1中测试。

String的搜索函数也很有用。它搜索给定字符串中的字符和sub_string。

'apple'.search('pl')返回2

'apple'.search('x')返回-1

var inputString = "this is home"; Var findme = "home"; if (inputString.indexOf(findme) > -1) { Alert(“找到了”); }其他{ Alert(“未找到”); }

演示:include()方法在整个字符串中查找“contains”字符,它将返回true。

var string = "这是一个tutsmake.com,本教程包含javascript include()方法的例子。" str.includes(“包含”); // this的输出 真正的