简体   繁体   中英

How to check if two strings contain same characters in Javascript?

I have two strings:

var a = 'ABCD';
var b = 'DEFG';

I need to compare these variables to check if there is not a common CHARACTER in the two strings.

So for this case return false (or do something...) because D is a common character in them.

You could merge the two strings then sort it then loop through it and if you find a match you could then exit out the loop.

I found this suggestion on a different stack overflow conversation:

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)    

So if you merge the strings together, you can do the above to use a regexp, instead of looping.

Thank you every one. I tried your solutions, and finally got this :

  • Merging my two strings into one
  • to Lower Case,
  • Sort,
  • and Join,
  • using Regex Match if the Final Concatenated string contains any repetitions,
  • Return 0 if no Repeat occur or count of repeats.

     var a; var b; var concatStr=a+b; checkReptCharc=checkRepeatChrcInString(concatStr); function checkRepeatChrcInString(str){ console.log('Concatenated String rec:' + str); try{ return str.toLowerCase().split("").sort().join("").match(/(.)\\1+/g).length; } catch(e){ return 0; } }

I was also searching for solution to this problem, but came up with this:

a.split('').filter(a_ => b.includes(a_)).length === 0

Split a into array of chars, then use filter to check whether each char in a occurs in b . This will return new array with all the matching letters. If length is zero, no matching chars.

add toUpperCase() to a & b if necessary

因此,如果它只使用 .split('') 在单独的字符串数组中复制字符串,那么我会分别对两个字符串进行排序,然后进行二分查找,从长度最短的数组开始,如果长度相同就使用第一个,逐个字符地搜索它是否在另一个字符串中。

This is obviously too late to matter to the original poster, but anyone else who finds this answer might find this useful.

var a = 'ABCD';
var b = 'DEFG';

function doesNotHaveCommonLetter(string1, string2) {
    // split string2 into an array
    let arr2 = string2.split("");
    // Split string1 into an array and loop through it for each letter.
    // .every loops through an array and if any of the callbacks return a falsy value,
    //     the whole statement will end early and return false too.
    return string1.split("").every((letter) => {
        // If the second array contains the current letter, return false
        if (arr2.includes(letter)) return false;
        else {
            // If we don't return true, the function will return undefined, which is falsy
            return true;
        } 
    })
}

doesNotHaveCommonLetter(a,b) // Returns false
doesNotHaveCommonLetter("abc", "xyz") // Returns true
const _str1 = 'ABCD';
const _str2 = 'DEFG';

function sameLetters(str1, str2) {
  if(str1.length !== str2.length) return false;
  
  const obj1 = {}
  const obj2 = {}
 
 for(const letter of str1) {
    obj1[letter] = (obj1[letter] || 1) + 1
 } 
 for(const letter of str2) {
    obj2[letter] = (obj2[letter] || 1) + 1
 }
  
 for(const key in obj1) {
    if(!obj2.hasOwnProperty(key)) return false
    if(obj1[key] !== obj2[key]) return false
  }
  return true
}

sameLetters(_str1, _str2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM