Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain method to returned string value

Tags:

javascript

Below there's a function that returns the string depending on a current language, for example if the language is "it"

var currLang = "it";
var language = (function () {
  /*this.uppercase = function(){
    // the following is more like a pseudo since makes no sense:
    return this.toUpperCase(); // I mean, it's wrong... I know :(
  };*/
  return {
    it : {
      hi : "ciao"
    },
    es : {
      hi : "ola"
    }
  }[ currLang ];  
})();


console.log( language.hi ); // ciao
console.log( language.hi.toUpperCase() ); // CIAO

Above I'm happy to use it like it is, chaining the JS's vanilla String prototype toUpperCase, but I was just wondering:
how to chain a method we created... like .toUpperCase or a custom one like .toFirstUppercase() ? For example:

language.hi.toFirstUppercase() 

but keeping our toFirstUppercase inside the language function?

My problem is that language.hi already returns a string, I know that .toUpperCase() operates on the object "String".toUpperCase() but how to make a custom method inside my app that will help to achieve the same?

Please, if the question is not clear I'd like to improve it so let me know! Thx for any suggestion

like image 407
Ginnani Avatar asked Apr 11 '26 02:04

Ginnani


1 Answers

Use prototypes and add a toFirstUpperCase method to the String.prototype object. This will instantiate an instance of the toFirstUpperCase closure function for every instance of String:

var currLang = "it";
var language = (function () {
  /*this.uppercase = function(){
    // the following is more like a pseudo since makes no sense:
    return this.toUpperCase(); // I mean, it's wrong... I know :(
  };*/
  return {
    it : {
      hi : "ciao"
    },
    es : {
      hi : "ola"
    }
  }[ currLang ];  
})();

String.prototype.toFirstUpperCase = function()
{
    return this[0].toUpperCase() + this.slice(1, this.length);
}


console.log( language.hi ); // ciao
console.log( language.hi.toUpperCase() ); // CIAO
console.log( language.hi.toFirstUpperCase() ); // Ciao