How to check two string have same characters including special characters

后端 未结 6 1052
陌清茗
陌清茗 2021-01-25 04:41

I have two question

1) how can I check two shuffle string have same characters Like I have

var str1 = \"ansar@#//1\";
var str2 = \"@#//sanra1\";
         


        
6条回答
  •  孤城傲影
    2021-01-25 05:11

    Consider these implementations:

    1)

    var str1 = "ansar@#//1";
    var str2 = "@#//sanra1";
    
    function first(str1, str2) {
        return Array.prototype.every.call(str1, function(c) {
            return str2.indexOf(c) > -1;
        }, this);
    }
    
    console.log(first(str1, str2));
    
    var str1 = "ansar@#//123";
    var str2 = "@#//sanra";
    
    function second() {
        return Array.prototype.filter.call(str1, function(c) {
            return str2.indexOf(c) === -1;
        }, this).join('');
    }
    
    console.log(second(str1, str2));
    

    Update for checking if strings contain same characters you can use ES6 Set:

    const checkIfStringsContainSameCharacters = (string1, string2) => {
      return new Set(string1).size === new Set(string1 + string2).size;
    }
    

提交回复
热议问题