main.js (1780B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isString = require( './../../is-string' ).isPrimitive; 24 25 26 // VARIABLES // 27 28 // Character codes: 29 var ZERO = 48; 30 var NINE = 57; 31 var A = 65; 32 var Z = 90; 33 var a = 97; 34 var z = 122; 35 36 37 // MAIN // 38 39 /** 40 * Tests whether a string contains only alphanumeric characters. 41 * 42 * @param {*} x - value to test 43 * @returns {boolean} boolean indicating if a string contains only alphanumeric characters 44 * 45 * @example 46 * var out = isAlphaNumeric( 'abc123def456' ); 47 * // returns true 48 * 49 * @example 50 * var out = isAlphaNumeric( '0xffffff' ); 51 * // returns true 52 * 53 * @example 54 * var out = isAlphaNumeric( '123' ); 55 * // returns true 56 * 57 * @example 58 * var out = isAlphaNumeric( '' ); 59 * // returns false 60 * 61 * @example 62 * var out = isAlphaNumeric( 123 ); 63 * // returns false 64 */ 65 function isAlphaNumeric( x ) { 66 var len; 67 var ch; 68 var i; 69 if ( !isString( x ) ) { 70 return false; 71 } 72 len = x.length; 73 if ( len === 0 ) { 74 return false; 75 } 76 for ( i = 0; i < len; i++ ) { 77 ch = x.charCodeAt( i ); 78 if ( 79 (ch < ZERO || ch > NINE) && 80 (ch < a || ch > z) && 81 (ch < A || ch > Z) 82 ) { 83 return false; 84 } 85 } 86 return true; 87 } 88 89 90 // EXPORTS // 91 92 module.exports = isAlphaNumeric;