Home > Blockchain >  Remove all chars except variable
Remove all chars except variable

Time:12-01

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.

CodePudding user response:

You can use .replace method instead

OR

you can use more inefficient way to do same

string.split('').filter(c => c === char).join('')
  • Related