Home > Net >  How could i select a specific characters in an array at JavaScript
How could i select a specific characters in an array at JavaScript

Time:08-01

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;
  }
};

CodePudding user response:

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)
}

console.log(extractPassword(['a', '-', '~', '1', 'a', '/']));
console.log(extractPassword(['~', 'A', '7', '/', 'C']))

CodePudding user response:

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, ''))

  • Related