Reputation: 2494
I have string with 2 or 3 words:
'apple grape lemon'
'apple grape'
I need to get first char from all words. my regex:
/^(\w).*?\ (\w).*?\ ?(\w?).*?$/
For all strings this regex get only first char of 2 words.
How to fix?
Upvotes: 0
Views: 1942
Reputation: 3618
In regexp "words" don't mean only letters. In JavaScript \w
is equals [A-Za-z0-9_]
. So if you want only letters in your result, you can use [A-Za-z]
.
Upvotes: 0
Reputation: 43673
The most simple way would be:
firstLetters = (m = str.match(/\b\w/g))? m.join('') : '';
Upvotes: 0
Reputation: 3955
If you work with javascript, you don't need to regex the hell out of a simple problem.
To get the first letter, just do that:
var aString = 'apple bee plant';
var anArray = aString.split(' ');
for(var aWord in anArray) {
var firstLetter = aWord.charAt(0);
}
Upvotes: 2
Reputation: 44259
You cannot do this with one regex (unless you are using .NET). But you can use a regex that matches one first character of a word, then get all the matches, and join them together:
var firstLetters = '';
var match = str.match(/\b\w/g)
if (match)
firstLetters = match.join('');
Of course if you just want to get the letters on their own, there is no need for the join
, since the match
will simply be an array containing all those letters.
You should not, that \w
is not only letters, but digits and underscores, too.
Upvotes: 4
Reputation: 1131
Regular expressions are a regular language, such that you cannot have this kind of repetition in them. What you want is to cut the string into individual tokes (which can be done via regular expressions to match the separator) and then apply an regular expression on each token. To get the first char from each word it is faster to use a substring operation instead of a regular expression.
The problem with your regex is that the .*?
after the second word eats up all the following content as everything afterwards is optional. This could be solved, but I personally think it makes things more complicated than required.
Upvotes: 0