Question

I've done some research and can't seem to find a way to do this. I even tried using a for loop to loop through the string and tried using the functions isLetter() and charAt(). I have a string which is a street address for example:

var streetAddr = "45 Church St";

I need a way to loop through the string and find the first alphabetical letter in that string. I need to use that character somewhere else after this. For the above example I would need the function to return a value of C. What would be a nice way to do this?

Was it helpful?

Solution

Maybe one of the shortest solutions:

'45 Church St'.match(/[a-zA-Z]/).pop();

Since match will return null if there are no alphanumerical characters in a string, you may transform it to the following fool proof solution:

('45 Church St'.match(/[a-zA-Z]/) || []).pop();

OTHER TIPS

Just check if the character is in the range A-Z or a-z

function firstChar(inputString) {
    for (var i = 0; i < inputString.length; i += 1) {
        if ((inputString.charAt(i) >= 'A' && inputString.charAt(i) <= 'Z') || 
            (inputString.charAt(i) >= 'a' && inputString.charAt(i) <= 'z')) {
            return inputString.charAt(i);
        }
    }
    return "";
}

console.assert(firstChar("45 Church St") === "C");
console.assert(firstChar("12345") === "");

This can be done with match

"45 Church St".match(/[a-z]/i)[0]; // "C"

This code example should get the job done.

function numsNletters(alphanum) {
    firstChar=alphanum.match(/[a-zA-Z]/).pop();
    numsLetters=alphanum.split(firstChar);
    numbers=numsLetters[0];
    // prepending the letter we split on (found with regex at top)
    letters=firstChar+numsLetters[1];
    return numbers+'|'+letters;
}

numsNletters("123abc"); // returns "123|abc";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top