How to check two string have same characters including special characters

后端 未结 6 1053
陌清茗
陌清茗 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:08

    This will return a true or false, if character in both string having the same character, and i think this is the most efficent way to do that.

    a)

    function hasSameCharacter(str1, str2) {
        let a = Array.prototype.every.call(str1, (char) => str2.indexOf(char) > -1, this);
        if (a) return Array.prototype.every.call(str2, (char2) => str1.indexOf(char2) > -1, this);
        else return false;
    }
    
    console.log(hasSameCharacter(str1, str2));
    

    b)

    function hasSameCharacter(str1, str2) {
        for (let i = 0; i < str1.length; i++) {
            if (str2.indexOf(str1[i]) <= -1) return false;
        }
        for (let i = 0; i < str2.length; i++) {
            if (str1.indexOf(str2[i]) <= -1) return false;
        }
        return true;
    }
    
    console.log(hasSameCharacter(str1, str2));
    

    Hope this helps, happy coding :)

提交回复
热议问题