As I tackle multiple coding challenges in preparation to join a coding bootcamp, I find myself stuck on the same problem for days.
Despite scouring the internet and experimenting with different solutions, I am unable to pass their specific test on the console.
Challenge:
Your task is to create a function called extractPassword that takes an array of characters (including some trash characters) and returns a string containing only valid characters (a - z, A - Z, 0 - 9).
Here are some examples:
extractPassword(['a', '-', '~', '1', 'a', '/']); // should return 'a1a'
extractPassword(['~', 'A', '7', '/', 'C']); // should return 'A7C'
Attempt 1:
Initially, I attempted using RegEx:
var newArray = [];
var extractPassword = function(arr){
console.log('arr: ' + arr);
return arr.join('').match(/[a-zA-Z0-9]/g);
};
console.log(extractPassword(['a','-','~','1','a','/']).toString().replace(/,/g, ''));
The output 'a1a' was what I desired, but unfortunately, it triggered an error: >>>Code is incorrect. We prefer a different approach instead of RegExs.
Attempt 2:
Subsequently, I opted for a function combined with a for loop and an if statement:
var newArray = [];
extractPassword(['a','-', '~', '1', 'a', '/']);
function extractPassword(arr){
console.log('arr: ' + arr);
var arrayToString = arr.join('');
console.log('arrayToString: ' + arrayToString);
for (var i = 0; i < arrayToString.length; i++){
var charCode = arrayToString.charCodeAt(i);
console.log('charCode ' + i + ':' + charCode);
if((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)){
newArray.push(arr[i]);
console.log('newArray: ' + newArray);
}
}
console.log('Final string: ' + newArray.join(''));
}
Although this approach also yielded 'a1a', the console still returned an error: >>Code is incorrect. Your function is not returning the correct value.
If anyone has an alternative solution to achieve the desired outcome, please share. Despite numerous attempts, I remain stuck and unable to progress.