7

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?

4 Answers 4

13

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I must admit after trying this solution, it is the best out of all of them.
Or '45 Church St'.replace(/^[^a-z]+/ig,'').substr(0,1) avoids the issues with match. Also ('45 Church St'.match(/[a-z]/i) || []).pop() saves 2 characters. :-)
Oh, there's also '45 Church St'.replace(/^[^a-z]+/ig,'')[0] but IE doesn't like that. :-(
7

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") === "");

2 Comments

+1 Because OP says I need a way to loop through the string and ...
Nothing wrong with this code, and the OP asked for a loop, but it's a great example of why regexes are worth the initial pain of learning.
6

This can be done with match

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

3 Comments

I've never used match before, where does the "C" value go to?
Currently it's not "going" anywhere, the line evaluates to it. You can use an = or a return or whatever you want to access it elsewhere
Though there will be another problem if the source string doesn't have any alphanumerical characters.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.