rex rex - 3 months ago 13
Javascript Question

How do I extract only alphabet from a alphanumeric string

I have a string "5A" or "a6". I want to get only "A" or "a" on the result. I am using the following but it's not working.

Javascript

var answer = '5A';
answer = answer.replace(/^[0-9]+$/i);
//console.log(answer) should be 'A';

Answer
 var answer = '5A';
 answer = answer.replace(/[0-9]/g, '');

g for global, no ^ or $, and '' to replace it with nothing. Leaving off the second parameter replaces it with the string 'undefined'.

I wondered if something like this this might be faster, but it and variations are much slower:

function alphaOnly(a) {
    var b = '';
    for (var i = 0; i < a.length; i++) {
        if (a[i] >= 'A' && a[i] <= 'z') b += a[i];
    }
    return b;
}

http://jsperf.com/strip-non-alpha

Comments