How can I compare two shuffled strings?

后端 未结 5 1031
盖世英雄少女心
盖世英雄少女心 2021-02-02 08:05

I have the following two strings:

var str1 = \"hello\";
var str2 = \"ehlol\";

How can I check whether both strings contain the same characters?

5条回答
  •  轮回少年
    2021-02-02 08:41

    Here's a modified version of Gurvinders answer.

    var str1 = "hello",
        str2 = "ehlol";
    
    // Add sort on prototype of String object
    String.prototype.sort = function () {
        return this.split('').sort().join('');
    };
    
    // First check if length of both is same
    var same = str1.length === str2.length && str1.sort() === str2.sort();
    console.log('Strings are same?', same);
    

提交回复
热议问题