Search code examples
javascriptstring-matching

regex for matching all characters in the string any where


I need a regex for matching all characters in the string. But it is not matter where that characters.

EG - Input array - [a, b, c] Following words should match

abc
axbxc
cybxbxca

But should not match following. Because these words has not all input charters.

axbxyz
bxba


Solution

  • You need a regexp like ^(?=.*a)(?=.*b)..., which you can build dynamically from the input:

    const inputArray = ['a', 'b', 'c'];
    
    let re = RegExp('^' + inputArray.map(x => '(?=.*' + x + ')').join(''))
    
    const words = [
        'abc',
        'axbxc',
        'cybxbxca',
        'axbxyz',
        'bxba',
    ];
    
    console.log(words.map(w => [w, re.test(w)]))

    If the input can contain regex special symbols, don't forget to escape them properly.