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

2

Best Answer


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

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]/greturn str.match(regex).filter(function(m,i,self) {return i == self.indexOf(m)}).join('')}var result = filterbychr('u23ntfb23nnfj3mimowmndnwm8') //=> "2bjd8"