Use Javascript to determine whether a string contains character or digit

Our Own Score

In this javascript tutorial, we will create a JavaScript program which will return true if the string contains only the uppercase or lowercase a to z letters and 0 to 9 digits. All other non a-z and non digit characters in the string will cause the program to return false. Here’s the entire script which uses JavaScript RegExp to shorten the for loop and thereby improving the overall performance.

function alphanumeric(string){
  if(string.length == 0)
	  return false
  let letter = /[A-Za-z0-9]/g
  let arr = string.split('')
  
  for(let i = 0; i < arr.length; i ++) {
	  if(!arr[i].match(letter))
	     return false
  }
  
  return true
}

As you can see from above, an empty string will also cause the program to return false.

0

Leave a Reply

avatar
  Subscribe  
Notify of