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
source to share
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(''));
To get all matches, use String.prototype.match()
with your Regex.
It will give you the following results:
2 b2 jd 8
source to share
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"
source to share