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));
本文由用戶 CliBitner 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!