0

How would I write a regex to take any input string and output only the letters?

input:

'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. '

output:

'thisisasentencethisisanexampleoftheinputstring'

3
  • Is µ a letter? How about é? Commented Feb 19, 2012 at 6:30
  • @muistooshort µ is a micron, éither way I'm looking for standard english alphabet. Commented Feb 19, 2012 at 6:32
  • µ is actually a lower case Greek letter that is also used as the Metric prefix for 10**-6. Commented Feb 19, 2012 at 6:39

2 Answers 2

2

You can remove all the non-letters like this:

var input = 'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. ';
var output = input.replace(/[^a-zA-Z]/g, "");

If you want the output to be all lowercase, then add .toLowerCase() onto the end like this:

var output = input.replace(/[^a-zA-Z]/g, "").toLowerCase();

By way of explanation, this regex matches all characters that are not a-z or A-Z. The g flag on the end of the regex tells it to replace all of them in the entire string (not just the first match it finds). And, the "" tells it to replace each match with an empty string (effectively removing all the match characters).

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

Comments

2
var text = 'This is a sentence. &)$&(@#1232&()$123!!ª•º–ª§∞•¶§¢• This is an example of the input string. ';
text.replace(/[^a-z]/ig, '');

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.