16

What would a regex string look like if you were provided a random string such as :

"u23ntfb23nnfj3mimowmndnwm8"

and I wanted to filter out certain characters such as 2, b, j, d, g, k and 8?

So in this case, the function would return '2bjd8'.

There's a lot of literature on the internet but nothing straight to the point. It shouldn't be too hard to create a regex to filter the string right?

ps. this is not homework but I am cool with daft punk

3
  • Which characters, specifically, would you like to include (or, alternatively, exclude)? Is the list provided in the question comprehensive?
    – jwueller
    Commented Aug 7, 2015 at 19:22
  • Do you only want one occurence of the given character, or all? Do you need them separated into an array, or should they be concatenated as a string?
    – holroy
    Commented Aug 7, 2015 at 19:38
  • @marcusdei why do you feel that this is a good task for a regular expression? I'm not saying it can't be done, but it's unnecessary, and overcomplicates the code.
    – zzzzBov
    Commented Aug 7, 2015 at 19:39

2 Answers 2

29

You need to create a regular expression first and then execute it over your string.

This is what you need :

var str = "u23ntfb23nnfj3mimowmndnwm8";
var re = /[2bjd8]+/g;
alert((str.match(re) || []).join(''));

To get all the matches use String.prototype.match() with your Regex.

It will give you the following matches in output:

2 b2 j d 8

8
  • Thanks a lot, let me run some tests
    – Marco V
    Commented Aug 7, 2015 at 19:22
  • Output gives me "2". Sorry for my initial comment, I mis-read the question. I thought the OP wanted to exclude the character set, not include only the character set.
    – Jasper
    Commented Aug 7, 2015 at 19:32
  • 1
    If he wants an array of all the matches, he should apply str.match(re), maybe joining it with .join('') to concatenate all the matches into one string. This is what he expects from his function: He should apply str.match(re).join('');
    – rplantiko
    Commented Aug 7, 2015 at 19:32
  • 2
    Yeah .match() seems to be the way to go.
    – Jasper
    Commented Aug 7, 2015 at 19:34
  • Like it's said it will delete those letters, okay to get all the matches we just need to use String.prototype.match().
    – cнŝdk
    Commented Aug 7, 2015 at 19:34
8

You could use a character class to define the characters.

Using the match() method to analyze the string and then filter out the duplicates.

function filterbychr(str) {
  var regex = /[28bdgjk]/g
  return str.match(regex).filter(function(m,i,self) {
    return i == self.indexOf(m)
  }).join('')
}

var result = filterbychr('u23ntfb23nnfj3mimowmndnwm8') //=> "2bjd8"
1
  • @marcusdei, You're welcome, let me know if you need me to change anything.
    – hwnd
    Commented Aug 8, 2015 at 9:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.