Reputation: 491
I'm having troubles with REGEX trying to build one that would retrieve the first letter of a word and any other Capital letter of that word and each first letter including the any Capital letter in the same word
"WelcomeBack to NorthAmerica a great place to be" = WBTNAAGPTB
"WelcomeBackAgain to NorthAmerica it's nice here" = WBATNAINH
"Welcome to the NFL, RedSkins-Dolphins play today" = WTTNFLRSDPT
tried this juus to get the first 2 matches:
/([A-Z])|\b([a-zA-Z])/g
Any help is welcomed, thanks
Upvotes: 2
Views: 223
Reputation: 10476
You can try this, it will also take care of whitespaces
str = str.match(/([A-Z])|(^|\s)(\w)/g);
str = str.join('');
str=str.replace(/ /g,'');
return str.toUpperCase();
Upvotes: 1
Reputation: 2691
You can use regex as : /\b[a-z]|[A-Z]+/g;
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "WelcomeBack to NorthAmerica a great place to be";
var re = /\b[a-z]|[A-Z]+/g;
var found = str.match( re );
found.forEach(function(item, index) {
found[index] = item.toUpperCase();
});
document.write(found.join(''));
</script>
</body>
</html>
Upvotes: 1
Reputation: 1001
Try this:
let s = "WelcomeBack to NorthAmerica a great place to be";
s = s.match(/([A-Z])|(^|\s)(\w)/g); // -> ["W","B"," t", " N"...]
s = s.join(''); // -> 'WB t N...'
s = s.replace(/\s/g, ''); // -> 'WBtN...'
return s.toUpperCase(); // -> 'WBT ...'
/(?:([A-Z])|\b(\w))/g
matches every uppercase letter ([A-Z])
OR |
every letter (\w)
that follows the start of the string ^
or a whitespace \s
.
(I couldn't get the whitespace to not be captured for some reason, hence the replace
step. Surely there are better tricks, but this is the most readable I find.)
Upvotes: 1
Reputation: 627419
You need a regex that will match all uppercase letters and those lowercase letters that appear at the start of the string or after a whitespace:
var re = /[A-Z]+|(?:^|\s)([a-z])/g;
var strs = ["WelcomeBack to NorthAmerica a great place to be", "WelcomeBackAgain to NorthAmerica it's nice here", "Welcome to the NFL, RedSkins-Dolphins play today"];
for (var s of strs) {
var res = "";
while((m = re.exec(s)) !== null) {
if (m[1]) {
res += m[1].toUpperCase();
} else {
res += m[0];
}
}
console.log(res);
}
Here, [A-Z]+|(^|\s)([a-z])
matches multiple occurrences of:
[A-Z]+
- 1 or more uppercase ASCII letters|
- or(?:^|\s)
- start of string (^
) or a whitespace (\s
)([a-z])
- Group 1: one lowercase ASCII letter.Upvotes: 3