Open In App

JavaScript Program to Find Uncommon Characters of the two Strings

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, finding uncommon characters in two strings is the process of identifying the characters that exist in one string but not in the other string.

We can find these uncommon characters using various approaches that are mentioned below:

Using Sets

In this approach, we create two sets from string 1 and string 2, then using the set operations we find and combine the unique characters that are present in string 1 and string 2 but not in both, Lastly, we print the result as a space-separated string using the spread operator and join() method.

Syntax:

let mySet = new Set(); 

Example: The below example uses Sets to find uncommon characters of the two strings in JavaScript.

Javascript




let s1 = "characters";
let s2 = "alphabets";
let set1 = new Set(s1);
let set2 = new Set(s2);
let res = new Set([...set1].filter(
    char => !set2.has(char)).concat([...set2].filter(
        char => !set1.has(char))));
console.log([...res].join(' '));


Output

c r l p b

Using Array.filter() method

In this approach, we use Array.filter() method which filters out characters that are not present in the other string. Then, we concatenate these arrays and remove the duplicates using a Set, lastly, we print the result.

Syntax:

let newArray = originalArray.filter(callback(element[, index[, array]]) {
// return
});

Example: The below example uses the Array.filter() method to find uncommon characters of the two strings in JavaScript.

Javascript




let s1 = "characters";
let s2 = "alphabets";
let res = [...s1].filter(char => !s2.includes(char)).concat([...s2].filter(char => !s1.includes(char)));
console.log([...new Set(res)].join(' '));


Output

c r l p b

Using Logical OR Operation

In this approach, we combine two strings into the temp variable, then by using the logical OR operation we filter out characters that are present in either string1 or string2 but not in both. Lastly, we remove duplicates using Set and print the result using the console.log() function.

Syntax:

let res =str1.includes(char) || str2.includes(char); 

Example: The below example uses XOR Operation to find uncommon characters of the two strings in JavaScript.

Javascript




let s1 = "characters";
let s2 = "alphabets";
let temp = s1 + s2;
let res = [...temp].filter(char => {
    return (s1.includes(char)
        || s2.includes(char))
        && !(s1.includes(char)
            && s2.includes(char))
}
);
console.log([...new Set(res)].join(' '));


Output

c r l p b


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads