I'm looking for the fastest way to lowercase all letters that aren't a part of AND in a phrase. I want to leave AND
in its original case, whether it was and
or AND
should not change.
For example, barack AND obama
should test equal to Barack AND Obama
but not barack and obama
. (notice the case difference in and)
Here is one approach, but I wonder if there is a shorter way or rather a way that avoids iterators:
var str = 'Barack AND Obama'; // should be barack AND obama after
str = str.split(/\s+/g).map(function (s) {
return s.toLowerCase() != 'and' ? s.toLowerCase() : s;
}).join(' ');
You can lowercase every word that's not exactly AND using a negative lookahead:
str = str.replace(/\b(?!AND).+?\b/g, function(s) {
return s.toLowerCase();
});
I think pimvdb has the most elegant solution, but just for variety, here is another one.
var str = 'Barack AND Obama';
var arr = str.split(' ');
for(var i=0;i<arr.length;i++){
if (arr[i] != 'AND'){
arr[i] = arr[i].toLowerCase();
}
}
var ans = arr.join(" ");
It is not as elegant, but I find it slightly more human-readable and easier to modify if needed in the future, ie add to the list of words that should not be lowercased.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With