Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to return letters only

Tags:

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:

function rowOffset(sequence) {               console.log(sequence);             var matches = /^[a-zA-Z]+$/.exec(sequence);             console.log(matches);             var letter = matches[0].toUpperCase();             return letter; }  var x = "A01"; console.log(rowOffset(x)); 

My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z

like image 861
Crystal Avatar asked Apr 17 '14 15:04

Crystal


People also ask

How do I allow only letters and numbers in regex?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do I make an input field accept only letters in Javascript?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

How do I restrict only alphanumeric in Javascript?

You will use the given regular expression to validate user input to allow only alphanumeric characters. Alphanumeric characters are all the alphabets and numbers, i.e., letters A–Z, a–z, and digits 0–9.


1 Answers

You can use String#replace to remove all non letters from input string:

var r = 'AA18'.replace(/[^a-zA-Z]+/g, ''); //=> "AA" 
like image 141
anubhava Avatar answered Oct 06 '22 23:10

anubhava