[javascript] 자바 스크립트에서 입력 문자열에 숫자가 포함되어 있는지 확인

최종 목표는 입력 필드의 유효성을 검사하는 것입니다. 입력은 알파벳 또는 숫자 일 수 있습니다.



답변

내가 실수하지 않으면 질문에 “숫자”가 아니라 “숫자 포함”이 필요합니다. 그래서:

function hasNumber(myString) {
  return /\d/.test(myString);
}


답변

자바 스크립트를 사용하여이 작업을 수행 할 수 있습니다. Jquery 또는 Regex 필요 없음

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

구현하는 동안

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); }
else { alert('not number'); }

업데이트 : 문자열에 숫자가 있는지 확인하려면 정규 표현식을 사용하여 수행 할 수 있습니다

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}


답변

function validate(){
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');
}


답변

그것은 방탄은 아니지만 내 목적을 위해 노력했으며 누군가를 도울 것입니다.

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }


답변

JavaScript와 함께 정규 표현식 사용 . 정규 표현식은 / pattern / modifiers 형식으로 작성된 검색 패턴을 설명하기위한 특수 텍스트 문자열입니다. 여기서 “pattern”은 정규 표현식이고 “modifiers”는 다양한 옵션을 나타내는 일련의 문자입니다.
문자 클래스
          문자 그대로 경기 후 가장 기본적인 정규 표현식의 개념이다. 하나의 작은 문자 시퀀스가 ​​더 큰 문자 세트와 일치하게합니다. 예를 들어 [A-Z]대문자 알파벳을 \d의미 할 수 있으며 모든 숫자를 의미 할 수 있습니다.

아래 예에서

  • contains_alphaNumeric«문자열에 문자 또는 숫자 (또는 문자와 숫자)가 포함되어 있는지 확인합니다. 그만큼하이픈 (-) 무시됩니다 .
  • onlyMixOfAlphaNumeric «그것은 문자열이 모두 포함되어 있는지 확인 과 문자 순서가 순서 순서 .

예:

function matchExpression( str ) {
    var rgularExp = {
        contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
        containsNumber : /\d+/,
        containsAlphabet : /[a-zA-Z]/,

        onlyLetters : /^[A-Za-z]+$/,
        onlyNumbers : /^[0-9]+$/,
        onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
    }

    var expMatch = {};
    expMatch.containsNumber = rgularExp.containsNumber.test(str);
    expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
    expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);

    expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
    expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
    expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);

    return expMatch;
}

// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
    id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
    id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );

console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );

console.log( "Only Special symbols :\n ", matchExpression(id12) );

넣어 :

Only Letters:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
  {containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
  {containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
  {containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}

정규 표현식과의 Java 패턴 일치


답변

과잉이없는 숫자가 어떤 문자인지 테스트하여 필요에 따라 조정합니다.

const s = "EMA618"

function hasInt(me){
  let i = 1,a = me.split(""),b = "",c = "";
  a.forEach(function(e){
   if (!isNaN(e)){
     console.log(`CONTAIN NUMBER «${e AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i}`)
     c += e
     i++
   } else {b += e}
  })
  console.log(`STRING IS «${b}», NUMBER IS «${c}»`)
  if (i === 0){
    return false
    // return b
  } else {
    return true
    // return +c
  }
}


hasInt(s)


답변

그것을 확인하는 한 가지 방법은 문자열을 반복하고 숫자를 칠 때 true (또는 원하는 것에 따라 false)를 반환하는 것입니다.

function checkStringForNumbers(input){
    let str = String(input);
    for( let i = 0; i < str.length; i++){
              console.log(str.charAt(i));
        if(!isNaN(str.charAt(i))){           //if the string is a number, do the following
            return true;
        }
    }
}