Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lowercasing all words except AND

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(' ');
like image 259
Brian Cray Avatar asked Dec 07 '12 21:12

Brian Cray


2 Answers

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();
});
like image 190
pimvdb Avatar answered Sep 21 '22 17:09

pimvdb


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.

like image 22
Scott Avatar answered Sep 20 '22 17:09

Scott