Miet
Miet

Reputation: 45

How to use a function across multiple js files

I am pretty new to javascript, but I am trying the best I can and I could not find the answer or something that helped me.

I am trying to put spaces between thousands, but in different JS files. So I would like to define that function in an other file, so I can reuse it. This works:

var parts = item['effect-value'].toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
parts.join(".");

What I have tried is the following:

Global file:

   function addSeparator(){
       parts.toString().split(".");
       parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
       parts.join(".");
   }

or something like this…

$.fn.addSeparator = function(options) {
    var $this = this;

    var parts = options.replace;

    $this.html({
        parts.toString().split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        parts.join(".");
    })

    return $this;
};

The other files:

var parts = item['effect-value'];
addSeparator(parts);

Thank you in advance.

Upvotes: 2

Views: 2644

Answers (2)

Shauna
Shauna

Reputation: 9596

As long as the functions are in the global scope and are already loaded, they should work.

What's the order of your JavaScript file calls in your HTML? Files with dependency on other files should come after the ones on which they depend.

IE - Global, Separator, JS that uses Separator

Upvotes: 1

Jonatas Gusmão
Jonatas Gusmão

Reputation: 162

You're just running the function, not aplying to the var.

Try using like this:

     function addSeparator(input){
           var parts = input.toString().split(".");
           parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
           return parts.join(".");
       }
     var parts = addSeparator(item['effect-value']);

Upvotes: 1

Related Questions