[英]Regex to filter out certain characters
What would a regex string look like if you were provided a random string such as : 如果您提供了一个随机字符串,那么正则表达式字符串会是什么样子:
"u23ntfb23nnfj3mimowmndnwm8" “u23ntfb23nnfj3mimowmndnwm8”
and I wanted to filter out certain characters such as 2, b, j, d, g, k and 8? 我想过滤出某些字符,如2,b,j,d,g,k和8?
So in this case, the function would return '2bjd8'
. 所以在这种情况下,函数将返回'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. PS。 this is not homework but I am cool with daft punk 这不是家庭作业,但我很擅长愚蠢的朋克
You need to create a regular expression first and then execute it over your string
. 您需要先创建一个正则表达式,然后在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. 要获得所有匹配项,请将String.prototype.match()
与正则表达式一起使用。
It will give you the following matches in output: 它将在输出中为您提供以下匹配:
2 b2 jd 8 2 b2 jd 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. 使用match()
方法分析字符串,然后过滤掉重复项。
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.