3

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);
    }
});

5 Answers 5

1

You should allow only letters, dash and single quotes, like this:

newValue = orgValue.replace(/[^a-zA-Z'-]/g, "");

Anything else will be replaced by "".

Sign up to request clarification or add additional context in comments.

1 Comment

You mean - newValue = orgValue.replace(/[^a-zA-Z'-.]/g,"");
1

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

Comments

1

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();

}

Comments

1
"ABDHN'S-J34H@#$".replace(/[^\-'\w]/g, '')

Comments

-2
"ABDHN'S-J34H@#$".replace(/[0-9]|[\'@#$]/g, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.