0

If i have a string say, 1234 Newyork Street, America and i want to extract the first LETTER from the string.

I understand how to use

 string.charAt(0);

But this extracts for example '1' from the example above. How would i modify the code so if i enter

string.charAt(0);

I extract the first LETTER which is 'N'.

4 Answers 4

2
string.replace(/[^a-zA-Z]/g, '').charAt(0);

This will remove anything that is not a letter, then return the first letter.

Sign up to request clarification or add additional context in comments.

4 Comments

It's just the opposite. It will remove anything which is a letter :P
@mohamedrias What do you mean?
string = "1234 Newyork Street, America" string.replace(/[^a-zA-Z]/, '').charAt(0); output : "2" , its returning 2
@mohamedrias Ah, I get you now. Added global flag so it removes all non-letters, rather than just the first.
1

Use search to get the index of the first letter, then use charAt:

var s = "1234 Newyork Street, America";
s.charAt(s.search(/[a-zA-Z]/));

Comments

0

Both of these will work :

string.replace(/^[1-9\s]+/g,"")[0]

or

replace(/^[1-9\s]+/g,"").charAt(0)

Comments

0

You can use regular expression capturing to find the first letter:

var s = "1234 Newyork Street, America",
    result = s.match(/([a-zA-Z]).*/),
    firstLetter;

if(result) {
    firstLetter = result[1];
}

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.