Javascript program to get all unique characters from a string

In this JavaScript program, we will learn how to get all unique characters from a string. The program will take one string as input , remove all duplicate characters and print out a new string holding only unique characters of the string.

Method 1: By looping over the characters :

We can loop over the characters of a string and build one new string with only unique characters.

let givenStr = "Hello World";

let uniqueCharStr = "";

[...givenStr].forEach((c) =>
  uniqueCharStr.indexOf(c) == -1 ? (uniqueCharStr += c) : ""
);

console.log(uniqueCharStr);

Here, givenStr is the string given and uniqueCharStr is the final string holding only unique characters of givenStr. We are using one forEach loop to iterate over the characters of givenStr characters. For that, we are converting the string to character first.

Inside the loop, we are checking if the current iterating character exist or not in the final unique character string. If not, we are appending that character to the end of the string.

Javascript get unique character from a string

If you run it, it will print the below output :

Helo Wrd

Method 2: By using Set constructor :

Set is a collection of unique elements. If we pass one string to the set constructor, it will create one set of unique characters. Then again, we can convert that set to an array and array to a string :

let givenString = "abcdefgabcdefg";

let setArray = [...new Set(givenString)];

console.log(setArray.join(""));

Or you can write it in one line :

let givenString = "abcdefgabcdefg";

let finalString = [...new Set(givenString)].join("");

console.log(finalString);

Javascript get unique characters from string using Set

It will print abcdefg as the output.