REgular表达式 - 允许破折号?

时间:2012-08-06 13:21:02

标签: regex

我有以下javascript,不允许用户在字段中输入任何特殊字符,但我确实要做一个例外并允许短划线( - ):

function Validate(txt)
{
    txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r]+/g, '');
}

如何修改它以将短划线添加到允许列表?

4 个答案:

答案 0 :(得分:5)

要允许短划线(-),您只需将其更改为:txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r]+/g, '');即可:txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r-]+/g, '');

请注意,短划线是方括号内的特殊字符(表示范围),因此必须是方括号内的最后位置。

根据 @Tim Pietzcker 的评论,你也可以将其txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r\-]+/g, '');转义或放在前面:txt.value = txt.value.replace(/[^-a-zA-Z 0-9\n\r]+/g, '');

答案 1 :(得分:3)

在角色类的末尾添加一个破折号(作为最后一个角色):

txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r-]+/g, '');

答案 2 :(得分:1)

试试这个: [^ a-zA-Z 0-9 \ n \ r - ] +

Cool Site for Regex-testing

答案 3 :(得分:1)

txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r-]+/g, ''); 

如果短划线不在决赛中,你也可以试试这个

[^a-zA-Z 0-9\n\-\r]+ //I only test this on rubular

TEST

相关问题