2

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.

5
  • So what is the problem? Commented Mar 7, 2013 at 16:38
  • What's the question then? Commented Mar 7, 2013 at 16:39
  • As long as the function is in the global scope (i.e. you include the file with the .js function in it on the pages that call it) you can simply make a call to the function like so var parts = addSeparator(item['effect-value']); Commented Mar 7, 2013 at 16:42
  • Hello Brad and gdoron, it does not work and I can't tell why… It's a little bit struggling for me still. War10ck thank you, I will try to figure that out! Commented Mar 7, 2013 at 21:33
  • War10ck thank you, I did not understand at first but now it works! Commented Mar 8, 2013 at 7:51

2 Answers 2

1

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']); 
Sign up to request clarification or add additional context in comments.

3 Comments

That does not seem to work. The console says: "Uncaught TypeError: Cannot call method 'toString' of undefined" and "Uncaught TypeError: Cannot call method 'replace' of undefined", but thank you for your reply!
what's the value of item["effect-value"]?
It's json data (pure numbers)? Does that answer your question?
1

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

1 Comment

Thank you for your comment Shauna. It seems that I forgot to save the function into a variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.