I am trying to write a regex to match only words that contain only un-capitalized letters in a string, but cannot figure it out.
Example
var str = "What a wonderful Sunday Afternoon";
I have managed to match any words beginning with a capital letter using this regex var str1 = str.match(/[A-Z][a-z]+/g)
Here str1
returns [What, Sunday, Afternoon]
What I now want to do is write a regex that returns a
and wonderful
.
I am trying to write a regex to match only words that contain only un-capitalized letters in a string, but cannot figure it out.
Example
var str = "What a wonderful Sunday Afternoon";
I have managed to match any words beginning with a capital letter using this regex var str1 = str.match(/[A-Z][a-z]+/g)
Here str1
returns [What, Sunday, Afternoon]
What I now want to do is write a regex that returns a
and wonderful
.
3 Answers
Reset to default 5You don't need regular expressions for this.
Just split the string at whitespace, and then filter the array based on whether the word is lowercase.
Example Here
var string = "What a wonderful Sunday Afternoon";
var lowerCaseWords = string.split(' ').filter(function(word) {
return word === word.toLowerCase();
});
console.log(lowerCaseWords);
// ["a", "wonderful"]
You could use this regex.
\b([a-z]+)\b
Demo: https://regex101./r/uQ6lT4/1
Your current regex [A-Z][a-z]+
Says one capital letter then any amount of lowercase letters.
Without the [A-Z]
you're are just looking for all lowercase letters, so partial words are matched. Adding word boundaries will ensure the value is one word (excluding hyphenated words).
you can also use below approach
var string = "What a wonderful Sunday Afternoon";
string .split(' ').forEach(function(v,k){
if(/[a-z]/.test(v.charAt(0))){
console.log(v);
return v;
}
})
var string = "What a wonderful Sunday Afternoon";
string .split(' ').forEach(function(v,k){
if(/[a-z]/.test(v.charAt(0))){
console.log(v);
return v;
}
})