string 判断一个字符串是否只包含另一个字符串的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17339036/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:00:08  来源:igfitidea点击:

Function to determine if a string contains characters only from another

javascriptstringvalidationarrays

提问by gen

I'm working on a validation function for html input tags. I've the string of the value of the particular input and the string containing the allowed characters.

我正在研究 html 输入标签的验证功能。我有特定输入值的字符串和包含允许字符的字符串。

var allowed = 'abcdefghijklmnopqrstuvwxyz";
var value = element.value;

I'd like to write a function to determine if the valuecontains character only from the allowedstring. I'm looking for a straight-forward and simple solution. Any ideas?

我想编写一个函数来确定是否value只包含allowed字符串中的字符。我正在寻找一个直接而简单的解决方案。有任何想法吗?

回答by Ajouve

Yes you can use regex

是的,您可以使用正则表达式

function alphanumeric(inputtxt)  
{   
    var letters = /^[a-z]+$/;  
    //if you want upper and numbers too 
    //letters = /^[A-Za-z0-9]+$/;
    //if you only want some letters
    // letters = /^[azertyuiop]+$/;
    if(inputtxt.value.match(letters))  
    {  
        alert('Your registration number have accepted : you can try another');  
        document.form1.text1.focus();  
        return true;  
    }  
    else  
    {  
        alert('Please input alphanumeric characters only');  
        return false;  
    }  
} 

回答by Bali Ram Vyas

Use below function.

使用以下功能。

function isChar(str) {
  return /^[a-zA-Z]+$/.test(str);
}
var allowed = 'abcdefghijklmnopqrstuvwxyz';
if(isChar(allowed )){
    alert('a-z cool :)');
}else{
    alert('Enter only Char between a-z');
}

Demo Link

演示链接

回答by Varun Upadhyay

Here is an answer without the use of regex

这是不使用正则表达式的答案

function allLetter(inputtxt)
{
    var inputtxt_low = inputtxt.toLowerCase();
    inputtxt_low = inputtxt_low.split('');
    var alpha_arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ];
    var count;
    for(count = 0; count < inputtxt_low.length; count++)
    {
        if(alpha_arr.indexOf(inputtxt_low[count]) == -1)
        {
            inputtxt= '';
            break;
        }
    }
    return inputtxt;
}