Construct string via recursion JavaScript

We are required to write a recursive function, say pickString that takes in a string that contains a combination of alphabets and numbers and returns a new string consisting of only alphabets.

For example,

If the string is 'dis122344as65t34er',
The output will be: 'disaster'

Therefore, let's write the code for this recursive function ?

Syntax

const pickString = (str, len = 0, res = '') => {
    if(len 

Example

const str = 'ex3454am65p43le';
const pickString = (str, len = 0, res = '') => {
    if(len 

Output

The output in the console will be ?

example
can you do it
hello
this is the last example

How It Works

The function uses three parameters: the input string, current position (len), and the result string (res). At each recursive call, it checks if the current character is a digit using parseInt(). If it's a digit, an empty string is added; otherwise, the character is appended to the result.

Alternative Approach Using isNaN

const pickStringAlt = (str, len = 0, res = '') => {
    if(len >= str.length) return res;
    
    const char = isNaN(str[len]) ? str[len] : '';
    return pickStringAlt(str, len + 1, res + char);
};

console.log(pickStringAlt('h3e2l1l4o w6o9r8l7d'));
console.log(pickStringAlt('j4a3v2a1s5c6r7i8p9t'));
hello world
javascript

Conclusion

Recursive string construction allows elegant character filtering. The function builds the result by examining each character and making a recursive call until the entire string is processed.

Updated on: 2026-03-15T23:18:59+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements