JavaScript Program to Test if Kth Character is Digit in String
Last Updated :
06 Nov, 2023
In this article, we are Given a String, we will check if the Kth index element is a digit or not. If it is a digit then we will print true else we will print false.
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:
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
let test_str = 'geeksgeeks' ;
console.log( "The original string is : " + test_str);
let K = 5;
let num_str = "0123456789" ;
let res = num_str.includes(test_str.charAt(K));
console.log( "Is Kth element String : " + res);
|
Output
The 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
let test_str = 'geeks4geeks' ;
console.log( "The original string is : " + test_str);
let K = 5;
let pattern = /\d/;
let match = test_str.charAt(K).match(pattern);
let res = !!match;
console.log( "Is Kth element String : " + res);
|
Output
The original string is : geeks4geeks
Is Kth element String : true
Share your thoughts in the comments
Please Login to comment...