简体   繁体   中英

How can I build a regex to exclude all, except letters and numbers?

I need to return a filtered string with "a1a" from the following function.

I've tried several regexes but nothing. On top of all, I can't use methods (part of the challenge).

let extractPassword = function(arr) {
  let toString = "";
  for (let i in arr) {
    if ( arr[i] === /[A - Za - z0 -9]/) {
      toString += arr[i];
    }
    console.log(toString);
  }
};

extractPassword(["a", "-", "~", "1", "a", "/"]);

Any ideas?

Thank you.

Your code has a few problems.

  1. Remove the spaces inside the regex. AZ and A - Z do not mean the same thing. The first indicates you want to match any letter between A and Z inclusive. The latter indicates you want to match A , - , or Z .

  2. Use the test(...) method on the regex object to determine whether the string matches the regular expression pattern. A string cannot ever be equal to the regex object.

  3. The toString variable is a commonly used method. This makes your code a little less clear. I gave it a more appropriate name, extractedPw , which better denotes its purpose.

  4. You are not returning anything from your method. The name " extract password" suggests it will return an extracted password.

let extractPassword = function(arr) {
  let extractedPw = "";
  for (let i in arr) {
    if (/[A-Za-z0-9]/.test(arr[i])) {
      extractedPw += arr[i];
    }
    console.log(extractedPw);
  }
  return extractedPw;
};

extractPassword(["a", "-", "~", "1", "a", "/"]);

So, you just want to take the characters that match your regex and join them?

 let extractPassword = arr => arr.filter(v => v.match(/[A-Za-z0-9]/)).join(''); let pw = extractPassword(["a", "-", "~", "1", "a", "/"]); console.log(pw);

If you mean filter and join are prohibited, then you can reinvent them trivially:

 let extractPassword = arr => { let r = ''; for (let v of arr) if (v.match(/[A-Za-z0-9]/)) r += v; return r; }; let pw = extractPassword(["a", "-", "~", "1", "a", "/"]); console.log(pw);

String === regular expression doesn't work.

Instead use RegExp.prototype.test()

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Your code could look like this:

 let extractPassword = function(arr) { let toString = ""; const regex = /[A-Za-z0-9]/; for (let i in arr) { if (regex.test(arr[i])) { toString += arr[i]; } } return toString; }; console.log(extractPassword(["a", "-", "~", "1", "a", "/"]));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM