驗證字串是否包含英文字元、數字或者漢字程式碼例項

admin發表於2017-03-10

本章節分享一段程式碼例項它實現了能夠驗證字串中是否包含英文字元、數字或者漢字的功能。

此函式比較靈活,能夠進行定製,程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
function done(input, withEnglishCharacter, withNumber, withChineseCharacter) { 
  if (!Boolean(withEnglishCharacter) && !Boolean(withNumber) && !Boolean(withChineseCharacter)) { 
    return false; //如果英文字母、數字和漢字都沒有,則返回false 
  } 
  var pattern = '^['; 
    if (Boolean(withEnglishCharacter)) { 
      pattern += 'a-zA-Z'; 
    } 
    if (Boolean(withNumber)) { 
      pattern += '0-9'; 
    } 
    if (Boolean(withChineseCharacter)) { 
      pattern += '\\u4E00-\\u9FA5'; 
    } 
  pattern += ']+$';
 
  var regex = new RegExp(pattern); 
  if (input.match(regex)) { 
    return true; 
  }
  else {
    return false; 
  } 
}
var one = "antzone";
var two = "softwhy.com888";
var three = "螞蟻部落good";
console.log(done(one, true, true, false));
console.log(done(two, false, true, false));
console.log(done(three, true, false, true));

相關文章