Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  135] [ 1]  / answers: 1 / hits: 40524  / 11 Years ago, wed, september 4, 2013, 12:00:00

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';

More From » jquery

 Answers
60
 var answer = '5A';
answer = answer.replace(/[^A-Za-z]/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


[#75891] Tuesday, September 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lelasamiraa

Total Points: 208
Total Questions: 99
Total Answers: 107

Location: Uzbekistan
Member since Tue, Nov 30, 2021
3 Years ago
;