问题描述:

I want to allow 0-9,a-z,A-Z and the special characters . , @ & ( ) {} [ ] : ; in text box.

Please help me to write regular expression for that. Currently I have a code that replace none word character with empty data and I want to made changes so that it also allow above special character.

function deleteSpecialChar(txtName, event) {

if (txtName.value != '' && txtName.value.match(/^[\w]+$/) == null) {

txtName.value = txtName.value.replace(/[\W]/g, '');

};

}

$('input[type=text]').live('keypress keyup keydown cut copy paste', function (event) {

deleteSpecialChar(this, event);

});

网友答案:

Just put what you want to remove in a set:

[^0-9a-zA-Z.,@&(){}\[\]:;]+

Use the test method, and you can use the same regular expression for the check and the replace, instead of having one positive and one negative:

function deleteSpecialChar(txtName, event) {
  var re = /[^0-9,a-z,A-Z\.,@&\(\)\{\}\[\]:;]+/g;
  if (txtName.value != '' && txtName.value.test(re)) {
    txtName.value = txtName.value.replace(re, '');
  };
}
网友答案:

Try

txtName.value = txtName.value.replace(/[^\w.,@&(){}\[\]:;]/g, '');

The character class starting with ^ is a negated class, so this will replace every character that is not in that class.

相关阅读:
Top