We
often need to find unique characters to work on different elements of any
string. For example, we have a string (‘hello world’) and now we want to find
the unique or unique characters in this string. In today's blog, we will
discuss some methods on how to easily solve this problem using JavaScript.
Using
for loop and includes method
function getUniqueCharacters(str) {
let uniqueChars = ''; // Empty string to store unique characters
for (let char of str) {
// If the character is not already in the unique string, add it
if (!uniqueChars.includes(char)) {
uniqueChars += char;
}
}
return uniqueChars;
}
// Example usage
const input = "hello world";
console.log(getUniqueCharacters(input)); // "helo wrd"
Using
filter method
function getUniqueCharacters(str) {
return str
.split('') // Splitting the string into an array of characters
.filter((char, index, arr) => arr.indexOf(char) === index) // Filtering only the unique characters
.join(''); // Converting the array back into a string
}
// Example usage
const input = "hello world";
console.log(getUniqueCharacters(input)); // "helo wrd"
Using
reduce method
function getUniqueCharacters(str) {
return str.split('').reduce((uniqueChars, char) => {
// If the character is not already in the unique string, add it
return uniqueChars.includes(char) ? uniqueChars : uniqueChars + char;
}, '');
}
// Example usage
const input = "hello world";
console.log(getUniqueCharacters(input)); // "helo wrd"
Using
regular expression (RegEx)
function getUniqueCharacters(str) {
return str.replace(/(.)(?=.*\1)/g, ''); // Retains the first occurrence of each character and removes the rest
}
// Example usage
const input = "hello world";
console.log(getUniqueCharacters(input)); // "helo wrd"
Bookmark
the website! If you like the post and don't forget to share the post so that
your friends don't miss it. Be sure to like and comment so that we can
constantly come up with new problems along with solutions and if you also have
any coding related problems, let us know in the comment box and we will try to
solve them, InshaAllah.