Is there any pre-built method for finding all permutations of a given string in JavaScript?

前端 未结 8 2135
遥遥无期
遥遥无期 2020-11-28 10:28

I\'m a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a give

8条回答
  •  北海茫月
    2020-11-28 10:51

    Assuming a large string to search, you could use a regular expression

    to examine a set of possibles that first matches the letters and the total number of letters,

    and return the matches that use the same letter set as the pattern.

    //(case-insensitive)

    function lettersets(str, pat){
        var A= [], M, tem,
        rx= RegExp('\\b(['+pat+']{'+pat.length+'})\\b', 'gi'),
        pattern= pat.toLowerCase().split('').sort().join('');
        while((M= rx.exec(str))!= null){
            tem= M[1].toLowerCase().split('').sort();
            if(tem.join('')=== pattern) A.push(M[1]);
        };
        return A;
    }
    

    lettersets(s, 'the').sort();

提交回复
热议问题