-1

This is the first time I am using Underscore.js. I have included the production underscore-min.js at the bottom of my page ( which is in Jade originally ), just before my custom script.

<script src="/javascripts/underscore-min.js">
<script src="/javascripts/custom.js">

Now, I call this function in my custom.js:

var selections = "Bold;Business-like;Charming";
var num_selections = _str.words( question.selected_words, ";").length;

Basically, I need to know the number of words selected and the native javascript method split returns 1 for even a blank string. But when I use this code, I get this error in my browser console: Uncaught ReferenceError: _str is not defined

I tried using this line before using _str, but then I get require is not defined:

var _  = require('underscore');

Or, perhaps I can put my question as How do we start using underscore functions in our front-end javascripts?

8
  • Are you using node? require is a node.js function. Commented Jun 28, 2016 at 15:48
  • @Jordan Yes, I'm using node.js but this error is coming on front-end. I need to use _str function in my front-end javascript. Commented Jun 28, 2016 at 15:49
  • So the variable selections is the reference for the data that you are looking to get the total? Commented Jun 28, 2016 at 16:12
  • 1
    When using split() did you try testing for empty string first? Commented Jun 28, 2016 at 16:19
  • 1
    The underscore function you are attempting to use _.words is a member of the Underscore.String library and not the Underscore.JS library. Additionally, you will need to install via NPM in Node.JS interpreter ($ npm install underscore.string). Commented Jun 28, 2016 at 21:55

1 Answer 1

1

Even though you are using node, require is not available on the front-end. Front-end javascript is not the same as back-end, nor do they directly interact. Underscore is called using _. All the methods available here: http://underscorejs.org/ are accessed via _.<method_name>. I am not too familiar with underscore and maybe you are using an older version but I cannot find _.str anywhere in the docs. So first, make sure you are using the correct notation for underscore _.<method_name> and make sure the function exists in the documentation. This fiddle shows some basic underscore functions: https://jsfiddle.net/mawpw2c5/

Sign up to request clarification or add additional context in comments.

1 Comment

I think you're right. I was trying to follow this answer stackoverflow.com/questions/33516370/… but now I think that references a new library underscore.string module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.