Replace number and character with jquery / javascript

Does anyone know how I can replace the number and character (excluding the dash and single quote)?

Example: if I have the string "ABDHN'S-J34H @ # $"; How can I replace the number and symbol with empty and return the value "ABDHN'S-JH" to me?

I have the following code to play all char and character for empty and return only 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);
    }
});

      

+3


source to share


5 answers


You should only allow letters, dashes and single quotes, for example:

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

      



Everything else will be replaced with "".

+1


source


You can use this regex:

string.replace(/^[a-zA-Z'-]+$/, '')

      



The caret ^ inside the character class [] will negate the match. This regular expression converts any characters other than a-z

, a-z

, single quote

and hyphen

to remove

+1


source


You can replace characters by running them through the keyboard code value on the keyboard.

Link to code point 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();

      

}

+1


source


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

      

+1


source


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

      

-2


source







All Articles