admin 管理员组文章数量: 1086019
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;
}
})
本文标签: regexOnly select words with all lower case characters javascriptStack Overflow
版权声明:本文标题:regex - Only select words with all lower case characters javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744067328a2527845.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论