javascriptregextypescriptstringjavascript-objects

Want to write regex in javascript which will check if all the mentioned chars exist at least ones


I have string s and need to check if that string contains every single alphabet from a to z. What will the regex be to check this condition? where s can be very big string with multiple words separated with space.

ex:

pattern.test("zy aemnofgbc jkhil pqasdfrs tuvrhfwx") 

should return true as it contains all a-z alphabets at least ones.

pattern.test("sdfasbcd effsdgh ijsfghtkl mnhtop qrsjht uvwmnmx yfdhjkd") 

should return false as it doesn't have alphabet z.

Looking for optimum solution.


Solution

  • First solution with regex - removes all non-alphabetic characters, duplicates, and compares the string length with 26.

    Second solution without regex, just checks is every alphabetic characters in string.

    const test1 = (str) => str.replace(/[^a-z]|(.)(?=.*\1)/gi, '').length === 26;
    
    const test2 = (str) => [...`abcdefghijklmnopqrstuvwxyz`]
      .every(ch => str.includes(ch));
    
    
    console.log(test1('zy aemnofgbc jkhil pqasdfrs tuvrhfwx'));
    console.log(test1('y aemnofgbc jkhil pqasdfrs tuvrhfwx'));
    
    console.log(test2('zy aemnofgbc jkhil pqasdfrs tuvrhfwx'));
    console.log(test2('y aemnofgbc jkhil pqasdfrs tuvrhfwx'));
    .as-console-wrapper{min-height: 100%!important; top: 0}