JavaScript Program to Test if Kth Character is Digit in String
Last Updated :
09 Jul, 2024
Testing if the Kth character in a string is a digit in JavaScript involves checking the character at the specified index and determining if it is a numeric digit.
Examples:
Input : test_str = ‘geeks9geeks’, K = 5
Output : True
Explanation : 5th idx element is 9, a digit, hence True.
Input : test_str = ‘geeks9geeks’, K = 4
Output : False
Explanation : 4th idx element is s, not a digit, hence False.
These are the following approaches by using these we can check whether the digit is present at the Kth index or not:
Using charAt():
In this approach, we check if the character at the Kth index in a string is a digit. It uses the 'charAt' method to retrieve the character at the specified index and the 'includes' method to check if the character exists in the numeric string "0123456789". The result is a boolean indicating whether the Kth element is a digit in the string.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing string
let test_str = 'geeksgeeks';
// Printing original string
console.log("The original string is : " + test_str);
// initializing K
let K = 5;
// Checking if Kth character is a
// digit in the string
// Getting numeric string
let num_str = "0123456789";
let res = num_str.includes(test_str.charAt(K));
// Printing result
console.log("Is Kth element String : " + res);
OutputThe original string is : geeksgeeks
Is Kth element String : false
Using regular expression:
In this approach, we are using the 'match' method to check if the character at the Kthj index in a string matches the regular expression pattern for a single digit `\d`. It stores the result in a boolean variable 'res' using the double negation '!!' to convert the match result to a boolean value. Finally, it prints whether the Kth element is a digit in the string.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initialize string
let test_str = 'geeks4geeks';
// Print original string
console.log("The original string is : " + test_str);
// Initialize K
let K = 5;
// Regular expression pattern for a single digit
let pattern = /\d/;
// Check if the Kth character
// matches the pattern
let match = test_str.charAt(K).match(pattern);
// Set the value of res based on the match result
let res = !!match;
// Print result
console.log("Is Kth element String : " + res);
OutputThe original string is : geeks4geeks
Is Kth element String : true
Using loop
This approach iterates over each character in the string and checks if the current index matches the kth position. If it does, it checks if the character is a digit. If the character is a digit it returns true otherwise, it returns false.
Example: This example shows the use of the above-explained approach.
JavaScript
function isKthCharacterDigit(str, k) {
for (let i = 0; i < str.length; i++) {
if (i === k - 1) {
return /\d/.test(str[i]);
}
}
// Return false if k is out of bounds
return false;
}
let string = "geeks57f2orgeeks";
let k = 5;
console.log(`Is the ${k}th character a digit: ${isKthCharacterDigit(string, k)}`);
OutputIs the 5th character a digit: false
Using codePointAt
In this approach we use the codePointAt method to get the Unicode code point of the character at the Kth position and check if it falls within the Unicode range of digits.
Example: This example shows the use of the above-explained approach.
JavaScript
function isKthCharacterDigit(str, k) {
const code = str.codePointAt(k);
return code >= 48 && code <= 57;
}
const string = "Hello123World";
const k = 5;
console.log(`Is the ${k}th character a digit: ${isKthCharacterDigit(string, k)}`);
OutputIs the 5th character a digit: true
Using Character Comparison
In the Character Comparison approach, we determine if the Kth character of a string is a digit by comparing it to character codes or ranges. Specifically, we check if the character falls between '0' and '9'.
Example: This example shows the use of the above-explained approach.
JavaScript
function isKthCharDigit(str, k) {
if (k < 0 || k >= str.length) {
return false;
}
const char = str[k];
return char >= '0' && char <= '9';
}
console.log(isKthCharDigit("geeks4geeks5", 5));
Using Array some Method
In this approach, we utilize the some method of arrays. We split the string into an array of characters and check if the character at the Kth index is a digit. The some method checks if any character at the Kth position is a digit using a helper function.
Example: This example shows the use of the above-explained approach.
JavaScript
// Function to check if Kth character is a digit using Array some method
function isKthCharDigit(str, k) {
const numStr = "0123456789".split('');
return numStr.some((digit) => digit === str.charAt(k));
}
// Test the function
const testStr = "geeks3geeks";
const k = 5;
console.log(`Is the ${k}th character a digit: ${isKthCharDigit(testStr, k)}`);
// Output
// Is the 5th character a digit: true
OutputIs the 5th character a digit: true
Using ASCII Values
In this approach, we directly use the ASCII values of characters to determine if the Kth character in a string is a digit. Digits '0' to '9' have ASCII values ranging from 48 to 57. We can compare the ASCII value of the character at the Kth index to this range.
Example: This example shows the use of the above-explained approach.
JavaScript
function isKthCharacterDigit(test_str, K) {
// Check if the Kth index is within the bounds of the string
if (K >= test_str.length || K < 0) {
return false;
}
// Get the ASCII value of the character at the Kth index
const charCode = test_str.charCodeAt(K);
// Check if the ASCII value is within the range of digit characters
return charCode >= 48 && charCode <= 57;
}
// Test cases
console.log(isKthCharacterDigit('geeks9geeks', 5)); // Output: true
console.log(isKthCharacterDigit('geeks9geeks', 4)); // Output: false
Similar Reads
JavaScript Program to Check if a String Contains Any Digit Characters
Here are the various methods to check if a string contains any digital character 1. Using Regular Expressions (RegExp)The most efficient and popular way to check if a string contains digits is by using a regular expression. The pattern \d matches any digit (0-9), and with the test() method, we can e
4 min read
JavaScript Program to Find iâth Index Character in a Binary String Obtained After n Iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes â01â and 1 becomes â10â. Find the (based on indexing) index character in the string after the nth iteration. Input: m = 5, n = 2, i = 3Output: 1Input: m = 3, n = 3, i = 6Output: 1Approach 1
6 min read
JavaScript Program to Check if Two Numbers have Same Last Digit
In this article, we will discuss how to check if two numbers have the same last digit in JavaScript. Checking the last digit of a number is a common requirement in programming tasks, and it can be useful in various scenarios. We will explore an approach using JavaScript to accomplish this task. Meth
4 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read
JavaScript Program to Check if a Number has Bits in an Alternate Pattern
JavaScript can be used to assess whether a given number follows an alternating pattern in its binary representation. By examining the binary digits of the number, one can determine if the sequence alternates between 0s and 1s, aiding in understanding the binary structure of the input. Examples: Inpu
2 min read
JavaScript Program to Multiply the Given Number by 2 such that it is Divisible by 10
In this article, we are going to implement a program through which we can find the minimum number of operations needed to make a number divisible by 10. We have to multiply it by 2 so that the resulting number will be divisible by 10. Our task is to calculate the minimum number of operations needed
3 min read
JavaScript Program to Check Whether a Number is a Duck Number
Duck numbers are special numbers that occur when a number has the digit '0' in it, but the '0' is not the first digit. numbers require the digit '0' to appear in the number, but not as the first digit. JavaScript provided several methods to check whether a number is a duck number which are as follow
2 min read
JavaScript Program to Check Whether a Number is Harshad Number
A Harshad number (also called Niven number) is a number that is divisible by the sum of its digits. In other words, if you take a number, sum up its digits, and if the original number is divisible by that sum, then it's a Harshad number. For example, 18 is a Harshad number because the sum of its dig
2 min read
JavaScript Program to Check Whether a Number is an Automorphic Number
Numbers, whose square ends with the same digits as the number itself are referred to as automorphic numbers, sometimes known as circular or circular-permuted numbers. Examples:Input: number = 5Output: YesExplanation: 5 is a automorphic number, because the square of 5 is 25 which ends with 5 the digi
3 min read
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string. Example: Input: "101010"Output: True, b
4 min read