Can anyone help at this exercise:
Create a function named extractPassword which takes an array of characters (which includes some trash characters) and returns a string with only valid characters (a - z, A - Z, 0 - 9).
Here's an example :
extractPassword(['a', '-', '~', '1', 'a', '/']); // should return the string 'a1a'
extractPassword(['~', 'A', '7', '/', 'C']); // should return the string 'A7C'
I have done until here :
var extractPassword = function() {
for (i = 0; i < extractPassword.length; i++) {
var output = "";
switch (extractPassword[i]) {
case '-':
case '~':
case '/':
break;
default:
output = output + extractPassword[i];
}
return output;
}
};
You can achieve this by using String.match() method with the help of RegEx.
Explanation of Regex /[a-zA-Z0-9]/ig :
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
] : end of character group
i : ignore case sensitivity
g : check for all occurrence in a provided string
Live Demo :
function extractPassword(arr) {
return arr.join().match(/[a-zA-Z0-9]/ig);
}
const res = extractPassword(['a', '-', '~', '1', 'a', '/']);
console.log(res.join(''));
Update : As author wants to do this with a plain JS without RegEx.
const str = [];
function extractPassword(arr) {
const arrStr = arr.join('');
for (var i = 0; i < arrStr.length; i++) {
var word = arrStr.charCodeAt(i);
if ((word > 47 && word < 58) || (word > 64 && word < 91) || (word > 96 && word < 123)) {
str.push(arr[i])
}
}
}
extractPassword(['a', '-', '~', '1', 'a', '/']);
console.log(str.join(''));
You can use regular expression [a-z0-9] means any English letter or number and g as a global flag and i as a case-insensitive.
const extractPassword = (str) => {
return str.join('').match(/[a-z0-9]/gi).join()
}
console.log(extractPassword(['a', '-', '~', '1', 'a', '/']));
console.log(extractPassword(['~', 'A', '7', '/', 'C']))
const extractPassword = (str) => {
return str.join('').match(/[a-z0-9]/gi)
}
console.log(extractPassword(['a', '-', '~', '1', 'a', '/']).toString().replace(/,/g, ''));
console.log(extractPassword(['~', 'A', '7', '/', 'C']).toString().replace(/,/g, ''))