正则表达式建议 - 从字符串中除了数字(0-9)和“/”之外删除所有字符

7

I need some advice using the RegExp Object.

It should only return numbers and the character "/" from the variable val ... I'm not experienced in the RegExp Object - this is what I got so far:

var val = $('.gallerystatus input').val();

var regExpr = new RegExp("^\d*\.?\d*$");

$('.gallerystatus input').val(  only 0-9 and "/"  );

Thanks for any advice!


这里有一点不太清楚,您想要返回什么内容。您是想返回单独的数字和“/”字符吗?还是只想过滤掉其他字符,返回只包含0-9和“/”的字符串? - Groovetrain
2种情况:过滤掉任何其他字符并返回仅包含0-9和'/'的字符串! - haemse
请仅翻译文本内容,不要解释它。如描述中所述,请不要看“^\d.?\d$”...也许这只是胡说八道 :-) - haemse
1个回答

21

这应该可以解决问题

value = value.replace(/[^\/\d]/g,'');
The trick is the ^ symbol. When it's inside a [] character class, the ^ is a negation operator for the class.
So in this example, the [] class is matching every character except slash and digits.
See it in action here: http://jsfiddle.net/5gMNg/

太完美了!回答得很好!必须等待5分钟才能将其投票为解决方案 :-) - haemse
1
另外,您没有提到在末尾使用“g”标志的重要性。如果您没有将其放在那里,它只会替换匹配组的第一个出现。 - Groovetrain
当我们有一个包含数字的字符串,例如10.5时,它返回的是105,这是错误的。 - Younes Zaidi
@YounesZaidi - 这个问题没有要求加点,所以我没有包含它。不过加点很容易的。 - Spudley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接