gpt4 book ai didi

javascript indexof regex A-Za-z0-9 总是返回 false

转载 作者:行者123 更新时间:2023-12-03 02:19:45 24 4
gpt4 key购买 nike

我创建了一个 JS fiddle https://jsfiddle.net/95r110s9/#&togetherjs=Emdw6ORNpc

HTML

<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />

JS

validateinputentries(){

landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;

goodcharacters = "/^[a-zA-Z0-9#.,;:'\s]+$/gi";

for (var i = 0; i < landlordstreetaddress2.length; i++){

if (goodcharacters.indexOf(landlordstreetaddress2.charAt(i)) != -1){

console.log('Character is valid');

}

}

}

它从输入中提取值,并运行包含 A-Z a-z 和 0-9 以及一些附加字符的 indexOf 正则表达式。

问题是它适用于 BCDEFG...etc 和 12345...etc 的条目,但是当我输入“A”或“Z”或“0”或“1”时,它返回不正确。

我需要它返回与 0123456789、ABCDEF...XYZ 和 abcdef...xyz 相同的内容

我应该指出,以下内容确实按预期工作:

var badcharacters = "*|,\":<>[]`\';@?=+/\\";
badcharacter = false;

//firstname
for (var i = 0; i < landlordfirstname.value.length; i++){

if (badcharacters.indexOf(landlordfirstname.value.charAt(i)) != -1){

badcharacter = true;
break;
}

if(landlordfirstname.value.charAt(0) == " "){

badcharacter = true;
break;
}

}

最佳答案

String.prototype.indexOf()

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

所以,您正在尝试搜索这个值"/^[a-zA-Z0-9#.,;:'\s]+$/gi",而“永远”不会在输入的字符串中找到。

您实际上想根据输入的值测试该正则表达式。

/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)

function validateinputentries() {
var landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;

if (/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)) {
console.log('Characters are valid');
} else {
console.log('Characters are invalid');
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />

关于javascript indexof regex A-Za-z0-9 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com