How to extract only alphabet from alphanumeric string

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

Javascript

var answer = '5A'; answer = answer.replace(/^[0-9]+$/i); //console.log(answer) should be 'A'; 
+4
source share
6 answers
  var answer = '5A'; answer = answer.replace(/[0-9]/g, ''); 

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

I wondered if something like this could speed things up, but it and the options 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

+10
source
 var answer = '5A'; answer = answer.replace(/[^az]/gi, ''); // [^az] matches everything but az // the flag `g` means it should match multiply occasions // the flag `i` is in case sensitive which means that `A` and `a` is treated as the same character ( and `B,b`, `C,c` etc ) 
+6
source

As you requested, you want to find the letter, and not delete the number (the same in this example, but may differ depending on your circumstances) - if this is what you want, there is another way that you can choose:

 var answer = "5A"; var match = answer.match(/[a-zA-Z]/); answer = match ? match[0] : null; 

He is looking for a match in the letter, not deleting the number. If a match is found, then match[0] will represent the first letter, otherwise match will be null.

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

You can also do this without regex if you care about performance;)

You have a few problems:

In general, I would advise you to learn a little about basic regular expressions. Here is a useful application to play with them: http://rubular.com/

+3
source

You can simplify @TrevorDixon and @Aegis answers using \d (digit) instead of [0-9]

  var answer = '5A'; answer = answer.replace(/\d/g, ''); 
+1
source

JavaScript: It will extract all alphabets from any string.

  var answer = '5A';
          answer = answer.replace (/ [^ a-zA-Z] / g, ''); 

 /*var answer = '5A'; answer = answer.replace(/[^a-zA-Z]/g, '');*/ $("#check").click(function(){ $("#extdata").html("Extraxted Alphabets : <i >"+$("#data").val().replace(/[^a-zA-Z]/g, '')+"</i>"); }); 
 i{ color:green; letter-spacing:1px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="text" id="data"> <button id="check">Click To Extract</button><br/> <h5 id="extdata"></h5> </div> 
0
source

Source: https://habr.com/ru/post/1500620/


All Articles