Javascript IndexOf 字符串中的整数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13928598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript IndexOf with integers in string not working
提问by Fab
Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
谁能告诉我为什么这不适用于整数但适用于字符?我真的很讨厌 reg 表达式,因为它们很神秘,但如果我也有的话。我还想在有效字符中包含“-()”。
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
回答by Ja?ck
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str
is contained within itself, e.g. 'hello world'.indexOf('world') != -1would return
true`.
如果字符串“方法”str
包含在其自身中,则返回 true ,例如 'hello world'.indexOf('world') != -1 would return
true`。
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val()
is already a string, so the .toString()
isn't necessary here.
的值$('#textbox1').val()
已经是一个字符串,所以.toString()
这里不需要。
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1
; it will almost always return false
unless you have a huge number like 10123456789
.
这就是出错的地方;有效地,这将执行'1234'.indexOf('0123456789') != -1
;它几乎总是会返回,false
除非你有一个像10123456789
.
What you could have done is test each character in str
whether they're contained inside '0123456789'
, e.g. '0123456789'.indexOf(c) != -1
where c
is a character in str
. It can be done a lot easier though.
什么,你可以做的是测试每一个字符str
,无论他们里面含有'0123456789'
,如'0123456789'.indexOf(c) != -1
其中c
在一个字符str
。不过,它可以更容易地完成。
Solution
解决方案
I know you don't like regular expressions, but they're pretty useful in these cases:
我知道你不喜欢正则表达式,但它们在这些情况下非常有用:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
解释
[0-9()]
is a character class, comprising the range 0-9
which is short for 0123456789
and the parentheses ()
.
[0-9()]
是一个字符类,包括0-9
缩写的范围0123456789
和括号()
。
[0-9()]+
matches at least one character that matches the above character class.
[0-9()]+
匹配至少一个与上述字符类匹配的字符。
^[0-9()]+$
matches strings for which ALL characters match the character class; ^
and $
match the beginning and end of the string, respectively.
^[0-9()]+$
匹配所有字符都匹配字符类的字符串;^
并分别$
匹配字符串的开头和结尾。
In the end, the whole expression is padded on both sides with /
, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$')
.
最后,整个表达式的两边都填充了/
,这是正则表达式分隔符。它是 的缩写new RegExp('^[0-9()]+$')
。
回答by MrCode
You are passing the entire list of validChars
to indexOf()
. You need to loop through the characters and check them one-by-one.
您正在传递validChars
to的整个列表indexOf()
。您需要遍历字符并一一检查它们。
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String()
, like this:
要在整数上使用它,您可以使用 将整数转换为字符串String()
,如下所示:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
回答by Cerbrus
Assuming you are looking for a function to validate your input, considering a validChars
parameter:
假设您正在寻找一个函数来验证您的输入,考虑一个validChars
参数:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Hyman's got a nice answer up here)
回答by Just_Mad
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
我只是猜测,但您似乎正在尝试查看电话号码。更改函数的一种简单方法是使用 RegExp 检查字符串值。
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
但它不检查字符串中的符号序列。
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
检查电话号码比较复杂,所以 RegExp 是一个很好的方法(即使你不喜欢它)。它看起来像:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\([0-9]{3}\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90"
. It not only checks for a list of characters, but also checks their sequence in string.
此变体将检查诸如"(123)456-78-90"
. 它不仅检查字符列表,还会检查它们在字符串中的序列。
回答by Fab
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
谢谢大家的答案!看起来我会使用正则表达式。我已经尝试了所有这些解决方案,但真的希望能够传入一串有效字符,但我将传入一个正则表达式。
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox
这适用于单词、字母,但不适用于整数。我想知道为什么它不适用于整数。我希望能够通过在 textBox 上使用自定义属性来模拟 MVC 中的 ajax 控件工具包中的 FilteredTextBoxExtender