Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  43] [ 7]  / answers: 1 / hits: 62319  / 10 Years ago, thu, april 17, 2014, 12:00:00

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


More From » regex

 Answers
16

Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.


Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.


Those two updates should get you going.




EDIT:


Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).


If you want to use match(), you need to change your code order just a bit to:


var matches = sequence.match(/[a-zA-Z]+/g);

To return an array of separate letters remove +:


var matches = sequence.match(/[a-zA-Z]/g);

[#71412] Wednesday, April 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daphnew

Total Points: 716
Total Questions: 113
Total Answers: 113

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;