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

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

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


当前回答

你们都想得太多了。只需使用一个简单的正则表达式,它是你最好的朋友。

var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."

var regex = /(pizza)/g // Insert whatever phrase or character you want to find

string1.test(regex); // => true
string2.test(regex); // => false

在5分钟内学会正则表达式?

其他回答

仅测试字母数字字符:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

正则表达式正在测试0-9、A-Z和A-Z字符集中的一个或多个(+),从输入的开始(^)开始,到输入的结束($)结束。

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

最快的字母数字方法可能是如上所述:在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中测试。

如果要搜索字符串开头或结尾的字符,还可以使用startsWith和endsWith

const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true

你们都想得太多了。只需使用一个简单的正则表达式,它是你最好的朋友。

var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."

var regex = /(pizza)/g // Insert whatever phrase or character you want to find

string1.test(regex); // => true
string2.test(regex); // => false

在5分钟内学会正则表达式?

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

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

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