Search code examples
javascriptarraysionic-frameworkangularjs-scope

Convert text input to lowercase - Javascript


Having trouble creating a case insensitive search in my Ionic app. I have the following that pushes tags into firebase. How can I convert the entire array to lowercase before going into the database?

$scope.addToTag = function(tag) {
  if ($scope.productTags.indexOf(tag) == -1)
    $scope.productTags.push(tag);

  $scope.productTags[tag] = true;

  var productTags = {};
  var addToTag = function(tag) {
    productTags[tag] = true;
  };
};

Thanks in advance!


Solution

  • You can use a map, for in, for of, for loop, for each ... to this. Combined with toLowerCase function for each element.

    Usage with map:

    var tags = ['ANDROID', 'iOS', 'Windows Phone'];
    
    var lowerCaseTags = tags.map(function (tag) {
        return tag.toLowerCase();
    });
    
    console.log(lowerCaseTags);
    

    Usage with for in:

    var tags = ['ANDROID', 'iOS', 'Windows Phone'];
    var lowerCaseTags = [];
    
    for (var tag in tags) {
        lowerCaseTags.push(tag.toLowerCase());
    }
    
    console.log(lowerCaseTags);
    

    Usage with for of:

    var tags = ['ANDROID', 'iOS', 'Windows Phone'];
    var lowerCaseTags = [];
    
    for (var tag of tags) {
        lowerCaseTags.push(tag.toLowerCase());
    }
    
    console.log(lowerCaseTags);
    

    Usage with for loop:

    var tags = ['ANDROID', 'iOS', 'Windows Phone'];
    var lowerCaseTags = [];
    
    for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        lowerCaseTags.push(tag.toLowerCase());
    }
    
    console.log(lowerCaseTags);
    

    Usage with forEach:

    var tags = ['ANDROID', 'iOS', 'Windows Phone'];
    var lowerCaseTags = [];
    
    tags.forEach(function(tag) {
        lowerCaseTags.push(tag.toLowerCase());
    });
    
    console.log(lowerCaseTags);