In the last few days I've been going around this particular problem that I can't manage to solve.
It goes like this:
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''
My code is
var new1 = [];
function extractPassword(array) {
for (var i = 0; i < array.length; i ) {
var y = array[i];
if (('a' <= y && y <= 'z') || ('A' <= y && y <= 'Z') || ('0' <= y && y <= '9')) {
new1.push(y);
}
}
}
extractPassword(['a', 'T', '~', 'L', '2']);
console.log(new1.join(''));
The console Output is correct 'aTL2' but it gives me an error still 'Code is incorrect, your function is not returning the correct value'.
I've tried putting the var new1 inside the function but then it says that the variable is undefined. I don't know what I can do to make this code work. Any help would be appreciated :)
CodePudding user response:
function extractPassword(array) {
var new1 = [];
for (var i = 0; i < array.length; i ) {
var y = array[i];
if (('a' <= y && y <= 'z') || ('A' <= y && y <= 'Z') || ('0' <= y && y <= '9')) {
new1.push(y);
}
}
return new1;
}
let a = extractPassword(['a', 'T', '~', 'L', '2']);
console.log(a.join(''));
CodePudding user response:
This can be easily achieved with regular expressions. The .join method combines all the array elements into a string, and the .replace method searches for all characters that are not a letter or number, and replaces them with "", giving the desired output
function extractPassword(input){
return input.join('').replace(/[^a-z0-9]/gi, '');
}
console.log(extractPassword(['a', '-', '~', '1', 'a', '/'])); // a1a
console.log(extractPassword(['~', 'A', '7', '/', 'C'])); // A7C
CodePudding user response:
I saw there are a lot of restrictions to what you can use just a tweak to your code that might work for you. you don't need to use an external variable for this if I understand correctly you only need a method.
function extractPassword(array) {
var password = '';
for (var i = 0; i < array.length; i ) {
var y = array[i];
if (('a' <= y && y <= 'z') || ('A' <= y && y <= 'Z') || ('0' <= y && y <= '9')) {
password = y;
}
}
return password;
}
console.log(extractPassword(['a', 'T', '~', 'L', '2']));
Here is another approach without using any variable here I am trying it with recursion, hope this works.
function extractPassword(array) {
if (array.length == 0) {
return ""
} else if (array.length == 1) {
if (('a' <= array[0] && array[0] <= 'z') || ('A' <= array[0] && array[0] <= 'Z') || ('0' <= array[0] && array[0] <= '9')){
return array [0]
}else {
return ""}
}
else {
return extractPassword(array.slice(0,1)) extractPassword(array.slice(1,array.length))
}
}
console.log(extractPassword(['a', 'T', '~', 'L', '2']));