Reputation: 43778
Does anyone know how can I replace the number and symbol (excluding dash and single quote)?
Example: if I have a string "ABDHN'S-J34H@#$"; How can I replace the number and symbol to empty and return me value "ABDHN'S-JH" ?
I have the following code to replay all the char and symbol to empty and only return me number
$(".test").keyup(function (e) {
orgValue = $(".test").val();
if (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 46) {
newValue = orgValue.replace(/[^\d.]/g, "");
$(".test").val(newValue);
}
});
Upvotes: 3
Views: 1432
Reputation: 43
You could replace symbols by skipping them through keycode value on the keyboard.
Link for keycode values for reglar keyboard: http://www.w3.org/2002/09/tests/keys.html
$("#your control").bind("keydown keyup", doItPlease);
function doItPlease(e)
{
// First 2 Ifs are for numbers for num pad and alpha pad numbers
if (e.which < 106 && e.which > 95)
{
return false; // replace your values or return false
}
else if (e.which < 58 && e.which > 47)
{
// replace your values or return false
} else {
var mycharacters = [8, 9, 33, 34, 35 // get your coders from above link];
for (var i = 0; i < mycharacters.length; i++) {
if (e.which == mycharacters[i]) {
// replace your characters or just
// return false; will cancel the key down and wont even allow it
}
e.preventDefault();
}
Upvotes: 1
Reputation: 14827
You can use this regex:
string.replace(/^[a-zA-Z'-]+$/, '')
The caret ^ inside a character class [] will negate the match. This regex will convert all characters other than a-z
, A-Z
, single quote
and hyphen
to empty
Upvotes: 1
Reputation: 1138
You should allow only letters, dash and single quotes, like this:
newValue = orgValue.replace(/[^a-zA-Z'-]/g, "");
Anything else will be replaced by "".
Upvotes: 1