find all letters without repeating regex

Viewed 89

help me please to find all letters in string without repeating using regex JS.

Examples:

let str = "abczacg";
str = str.match(/ pattern /); // return has to be: abczg

str = "aabbccdd" //return:abcd.

str = "hello world"//return: helo wrd

Is it possible?

Thank you!

2 Answers

Here is one approach. We can first reverse the input string. Then, do a global regex replacement on the following pattern:

(\w)(?=.*\1)

This will strip off any character for which we can find the same character later in the string. But, as we will be running this replacement on the reversed string, this has the actual effect of removing all duplicate letters other than their first occurrence. Finally, we reverse the remaining string again to arrive at the expected output.

var input = "abczacg";
var output = input.split("").reverse().join("").replace(/(\w)(?=.*\1)/g, "");
output = output.split("").reverse().join("");
console.log(output);

An alternative without using a regex using a Set:

[
  "abczacg",
  "aabbccdd",
  "hello world"
].forEach(s => {
  console.log([...new Set(s.split(''))].join(''))
})

Related