-3

I have a string like this

let string = 'hhhhhhdhhhhhfhhhh';

And a variable that's basically one single letter

let char = 'h';

How can I remove everything in string except for every occurence of char so that I get 'hhhhhhhhhhhhhhh'?

I've managed to do this so far:

let reg = new RegExp(char, "g");

let match = string.match(reg);

console.log(string.match(reg, ""));

This delivers me all matches of that specific char in the string

["h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h"]

but I'm not sure where to go from here to remove all letters except the defined variable (char).

Please view my fiddle for an example: https://jsfiddle.net/m7opadb8/6/

Also I apologize if this has been answered many times before, I couldn't seem to find one using RegExp.

Jeremy
  • 216
  • 4
  • 17
  • Here, `string.replace(new RegExp("[^"+char+"]+", "g"), "");` – Wiktor Stribiżew Nov 30 '21 at 14:46
  • 2
    What about joining the result? `match.join('')`? – evolutionxbox Nov 30 '21 at 14:49
  • And it's a perfect example of when using regex makes absolutely no sense. SO is meant for practical problems, and not totally unrealistic abstract examples. – 9ilsdx 9rvj 0lo Nov 30 '21 at 14:50
  • It would be prudent to escape the characters to be used in an regex if they come from an external source, e.g. a user: [Is there a RegExp.escape function in JavaScript?](https://stackoverflow.com/a/3561711/1115360) – Andrew Morton Nov 30 '21 at 14:53
  • 1
    Does this answer your question? [Replace all characters in a string except the ones that exist in an array](https://stackoverflow.com/questions/58439299/replace-all-characters-in-a-string-except-the-ones-that-exist-in-an-array) – F.Hoque Dec 01 '21 at 10:28

1 Answers1

1

You can use .replace method instead

OR

you can use more inefficient way to do same

string.split('').filter(c => c === char).join('')
Ruben Yeghikyan
  • 518
  • 2
  • 5
  • 19