How to use loop In Javascript
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.
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)}`);
Output
Is the 5th character a digit: false
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