How to use Character Comparison In Javascript
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.
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));
Output
true
JavaScript Program to Test if Kth Character is Digit in String
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:
Table of Content
- Using charAt():
- Using regular expression:
- Using loop
- Using codePointAt
- Using Character Comparison
- Using Array some Method