Regex for filtering specific characters

What would the regex string look like if you were given a random string like:

"u23ntfb23nnfj3mimowmndnwm8"

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

So in this case the function will return '2bjd8'

.

There is a lot of literature on the Internet, but nothing straightforward. Shouldn't it be too hard to create a regex to filter the string correctly?

ps. this is not homework, but I'm cool with daft punk

+3


source to share


2 answers


You need to create a regex and then execute it on your string.

This is what you need:

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

Run codeHide result




To get all matches, use String.prototype.match()

with your Regex.

It will give you the following results:

2 b2 jd 8

+7


source


You can use a character class to define characters.

Using a method match()

to parse the string and then filter out 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"

      

+5


source







All Articles