Coder Social home page Coder Social logo

underscore.string's Issues

format sentence

Hey -- great addition to Underscore; thanks :)

I just wrote a function that you might like to include; it's to take an array like ["John", "Paul", "George", "Ringo"] and format it with the syntax:

"John, Paul, George and Ringo."

It can take an array of strings or a JSON array and an iterator function to format them. There's a "max" parameter to limit the # of items used in the returned sentence.

Hope it's useful!

http://pastebin.com/CREV2a0k

please tag versions

Going forward it would be helpful if you could tag versions when they are created (and documented) in github, basically like underscore.js already does. It helps with tracking what version a developer has and ensuring we are in sync with online documentation. Also, I personally made the initial mistake of just grabbing 1.0.0 because it was the last tagged version. Thanks!

#titleize fails if string contain two spaces

Process:

> _.titleize('two words');
'Two Words'
> _.titleize('two  words');
TypeError: Object Two Words has no method 'titleize'
    at [object Context]:1:3
    at Interface. (repl:96:19)
    at Interface.emit (events:27:15)
    at Interface._ttyWrite (readline:309:12)
    at Interface.write (readline:147:30)
    at Stream. (repl:79:9)
    at Stream.emit (events:27:15)
    at IOWatcher.callback (net:489:16)
    at node.js:773:9

tokenize, string-join

Maybe I'm missing something, are these functions included?
They are some of the most useful string functions out there:

["a", "b", "c"].string-join("; ")

"a; b; c"
"a; b; c".tokenize("; ")
["a", "b", "c"]

update npm version

Hello there
Thanks for this project, it's super useful
I would like to use underscore.string with node too, but it looks like the version published is not up to date.
Could you push the last version ?

ljust alias for lpad

Maybe just me but this feels wrong.

lpad adds to the left so I think this is rjust

_.lpad("1", 8, '0')
-> "00000001";

the result is right justified no?

error due to "use strict"

I am getting following error while trying out this simple html

Uncaught TypeError: Cannot read property '_' of undefined (underscore.string:325)
<!DOCTYPE html>
<html>
  <head>
    <title>Underscore String Test</title>
    <script src="/assets/underscore.js" type="text/javascript"></script>
    <script src="/assets/underscore.string.js" type="text/javascript"></script>
  </head>
  <body></body>
</html>

It appears to be because of "use strict". If I comment that out, everything works fine. I am getting this error on FF Aurora as well as Chrome Dev Channel on Mac. Apparently, "use strict" is not allowing direct access to window object. So "root = this" is interpreted undefined instead of window object within the browser.

Thanks for any help here.

Problem with truncate

When using _('Hello').truncate(10) like in the example, I get the output "Hello..."

chop problem

Negative parm:

_.chop("some text",-1);

will produce an infinite loop.

Allow conflicting functions via type detection

Maybe you could suggest (or provide a helper function) that conflicting functions could override the underscore equivalents via wrappers that detect whether the argument passed is a String or other Object.

This would avoid potential bugs when someone uses the wrong function for the wrong type.

This is what I have done in my project and it seems to work well:

_.mixin(_.str.exports());

// functions that conflict with _ and _.prototype
_.mixin(_.reduce(['include', 'contains'], function(memo, f) {
  var str = _.str[f], und = _[f];
  memo[f] = function(obj) {
    return (_.isString(obj) ? str : und).apply(this, arguments);
  };
  return memo;
}, {}));

// functions that just conflict with _.prototype
_.each(['reverse'], function(f) {
  var wstr, str = _.str[f], wund = _.prototype[f]; 
  _.mixin({__tmp: str}); // get access to addToWrapper
  wstr = _.prototype.__tmp;
  _[f] = str;
  _.prototype[f] = function() {
    return (_.isString(this._wrapped) ? wstr : wund).apply(this, arguments);
  };
});

Thanks for a great library!

Default String method

We would like to add a default string method, which would return a default string for string values that are null, undefined or empty.

Example:

_('').defaultString('Test') => 'Test'
_(null).defaultString('Test') => 'Test'
_('Some String').defaultString('Test') => 'Some String'

Empty and whitespace-only strings

I would like to see an empty method that returns true if the string has a length of zero.

I would also like to see a method that returns true if the string only contains whitespace (I don't know how you would call that, blank maybe?).

escapeHTML

Hi!

The current implementation of the subj throws if typeof argument !== 'string' which is not uncommon case -- consider numbers, and especially undefined (which is very common case: _.escapeHTML(data['name']) when name is not in data)

Instead of endless sanity checks I propose to use something like:
return String(str||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');

TIA for feedback,
--Vladimir

startsWith and endsWith are too slow

I propose to change them to:

function strStarts(fnd,str,bol){
    return str.lastIndexOf(fnd,0)==0;
}

function strEnds(fnd,str,bol){
    var i=str.length-fnd.length;
    return str.lastIndexOf(fnd,i)==i;
}

It will be much faster.

It would also be interesting to add a new feature that allows to ignore-case. Something like:

function strStarts(fnd,str,bol){
    return (bol?str.toLowerCase().lastIndexOf(fnd.toLowerCase(),0):str.lastIndexOf(fnd,0))==0;
}

function strEnds(fnd,str,bol){
    var i=str.length-fnd.length;
    return (bol?str.toLowerCase().lastIndexOf(fnd.toLowerCase(),i):str.lastIndexOf(fnd,i))==i;
}

I ran some tests, and even with the new feature is faster than the current method.

Thanks for your time

dasherize & Consecutive Capital Letters: Unexpected Behavior?

This may or may not be expected behavior, however neither the documentation nor the current test cases cover this.

Example code:

_('thisIsATest').dasherize();

What I expect to get: this-is-a-test
What I actually get: this-is-atest

Because of this, you also end up with this outcome:

var foo = 'thisIsATest';
_(foo).chain().dasherize().camelize().value() === foo;  // is false

Basically, is the current behavior the expected behavior, or is this an overlooked edge case?

Get rid of sArgs

Cause it's freaking slow.

I guess the best way is to put something like str=str+'' every time we need to ensure argument is a String.

Pluralize function

_.pluralize('post') // => 'posts'
_.singularize('posts') // => 'post'

or

_.pluralize(1, 'post') //=> 'post'
_.pluralize(2, 'post') //=> 'posts'
_.pluralize(1, 'posts') //=> 'post'

"difference" bug following mixin of underscore.string

I'm using the latest version of underscore and underscore.string:

var _ = require('underscore')

_.difference([ 1, 2, 'c' ], [ 1, 2, 'cc' ]) // => [ 'c' ]
_.difference([ 1, 2, 'cc' ], [ 1, 2, 'c' ]) // => [ 'cc' ]

Suppose I ...

_.mixin(require('underscore.string'))

Now I'm seeing the following "bug" with _.difference:

_.difference([ 1, 2, 'c' ], [ 1, 2, 'cc' ]) // => [ ] // empty array! BUT should be [ 'c' ]
_.difference([ 1, 2, 'cc' ], [ 1, 2, 'c' ]) // => [ 'cc' ]

So underscore.string is altering the behavior of _.difference. It took me some time to figure out this was happening as it's subtle.

underscore.string doesn't mix in nicely with underscore.js in Node.js

I'm not sure what the best way to solve this is, but this has been driving me bonkers...the problem is the check at the top of underscore.string for the _ variable doesn't actually work reliably. Here's the test case:

var _ = require("underscore")
function Cat(){}
function Dog(){}
var cat = new Cat;
var dog = new Dog;
var animalsThatPurr = [cat];
console.log("Do dogs purr? " + _.include(animalsThatPurr, dog)); // prints false
_.mixin(require("underscore.string"));
console.log("Do they purr after including underscore.string? " + _.include(animalsThatPurr, dog)); // prints true

The problem is when underscore.string loads, _ will be undefined (since _ is scoped to the test file), so _.include (which was taken over by underscore.string) will fall back on to _.includes (also defined by underscore.string), which converts all/some of its args to strings, so you get a bunch of stringwise [Object object] comparisons.

underscore 1.1.7 union(..) bug with underscore.string 1.1.6

Execute this script with node.js and the specified versions:

var _           = require( 'underscore' );
    _.mixin(      require( 'underscore.string' ) );

var x = [{a: 5}, {b: 6}, {c: 7}];
var y = [];
console.log(_.union(x, y));

The result will include only the first element of x. Playing with it a bit, it looks like union(..) will keep integers in the array, while throwing out all objects after the first one.

Now comment out the mixin. The result will be correct.

node / common.js module (and package.json)

changing the bottom of underscore.strings.js to:

  // Integrate with Underscore.js
    if (root._) {
        root._.mixin(root._s);
    }

  // Export for Node.js use
    else if (module) {
        module.exports = root._s;
    }

... makes this https://gist.github.com/742422 possible

Ideally, there would also be a package.json so it could be installed with npm. Underscore is already available this way. In the meantime, being able to copy / paste the raw code (without editing) is still a welcome convenience...

Problems with numbers in IE6

There is an issue in IE6 when working with numbers. Example: _.trim("123") works fine, but _.trim(123) throws an error. The reason for this seems to be that IE6 doesn't automatically convert numbers to strings and thus all the String methods like replace() are missing.

A solution I found is to change each input str to str.toString(). However – and this is why I haven't created a commit yet – this needs many changes in many places. Now my questions would be:

  • Is there a simpler solution?
  • Is there a performance impact in doing .toString() everywhere?
  • Is it worth it?

In the business environment I'm using underscore.string in at the moment, IE6 is unfortunately still a reality, so my vote goes to "change it", even though I have solved my immediate problems with using .toString() in the place I need it. I could lend a hand with that. What do you think?

Update version in object

If you log the object you get:

{ VERSION: '1.2.0',
  isBlank: [Function],
  stripTags: [Function],
  ...

Dasherize - Accented/Special characters are now being converted to dashes

After the fix for issue #89, it seems all characters that are not [A-Za-z0-9] are being converted to dashes.
The behavior prior to the fix for #89 did not do this.

This is an issue when you have accented words and/or special characters like $ in the string you want to dasherize.

téléphone => t-l-phone
foo$bar => foo-bar

Email verification

A common string manipulation in JS is to check if an email is valid. Perhaps it belongs in this library? This is a feature request.

count doesn't work

_.str.count('x.xx....x.x','x') reports 3

The following works for me:

      str = ''+str; substr = ''+substr;
      var count = 0, index;
      for (var i=0; i < str.length;) {
        index = str.indexOf(substr, i);
        if (index<0) break;
        count++;
        i = index + substr.length;
      }
      return count;
    },

npm install undescore.string doesn't work

I am using node v0.6.10 and npm v1.1.0-3
These are the contents of npm-debug.log:

info it worked if it ends with ok
verbose cli [ 'node', '/usr/local/bin/npm', 'install', 'underscore.string' ]
info using [email protected]
info using [email protected]
verbose config file /home/alexandru/.npmrc
verbose config file /usr/local/etc/npmrc
verbose config file /usr/local/lib/node_modules/npm/npmrc
verbose caching /mnt/hgfs/oss/sum.js/text-summarization/package.json
verbose loadDefaults [email protected]
verbose from cache /mnt/hgfs/oss/sum.js/text-summarization/package.json
verbose cache add [ 'underscore.string@~2.0.0', null ]
silly cache add: name, spec, args [ undefined,
silly cache add: name, spec, args   'underscore.string@~2.0.0',
silly cache add: name, spec, args   [ 'underscore.string@~2.0.0', null ] ]
verbose parsed url { pathname: 'underscore.string@~2.0.0',
verbose parsed url   path: 'underscore.string@~2.0.0',
verbose parsed url   href: 'underscore.string@~2.0.0' }
silly cache add: name, spec, args [ 'underscore.string',
silly cache add: name, spec, args   '~2.0.0',
silly cache add: name, spec, args   [ 'underscore.string', '~2.0.0' ] ]
verbose parsed url { pathname: '~2.0.0', path: '~2.0.0', href: '~2.0.0' }
verbose addNamed [ 'underscore.string', '~2.0.0' ]
verbose addNamed [ null, '>=2.0.0- <2.1.0-' ]
silly name, range, hasData [ 'underscore.string', '>=2.0.0- <2.1.0-', false ]
verbose raw, before any munging underscore.string
verbose url resolving [ 'https://registry.npmjs.org/', './underscore.string' ]
verbose url resolved https://registry.npmjs.org/underscore.string
http GET https://registry.npmjs.org/underscore.string
ERR! Error: failed to fetch from registry: underscore.string
ERR!     at /usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/get.js:139:12
ERR!     at cb (/usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/request.js:32:9)
ERR!     at Request._callback (/usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/request.js:137:18)
ERR!     at Request.callback (/usr/local/lib/node_modules/npm/node_modules/request/main.js:109:22)
ERR!     at Request.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/request/main.js:198:58)
ERR!     at Request.emit (events.js:88:20)
ERR!     at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/request/main.js:195:10)
ERR!     at ClientRequest.emit (events.js:67:17)
ERR!     at CleartextStream.<anonymous> (http.js:1134:11)
ERR!     at CleartextStream.emit (events.js:67:17)
ERR! You may report this log at:
ERR!     <http://github.com/isaacs/npm/issues>
ERR! or email it to:
ERR!     <[email protected]>
ERR! 
ERR! System Linux 2.6.32-33-generic
ERR! command "node" "/usr/local/bin/npm" "install" "underscore.string"
ERR! cwd /mnt/hgfs/oss/sum.js/text-summarization
ERR! node -v v0.6.10
ERR! npm -v 1.1.0-3
ERR! message failed to fetch from registry: underscore.string
verbose exit [ 1, true ]

Cycle function

I'm interested in submitting a function that cycles through given arguments every time it is called with the same values. This can be used, for example, to alternate classes for table rows. Passing different arguments replaces previous cycle with a new cycle. Passing no arguments resets the cycle.

_.cycle('odd', 'even')
=> 'odd'
_.cycle('odd', 'even')
=> 'even'
_.cycle('odd', 'even')
=> 'odd'
_.cycle('one', 2, 'three')
=> 'one'
_.cycle('one', 2, 'three')
=> 2
_.cycle()
=> false
_.cycle('one', 2, 'three')
=> 'one'

I can submit a pull request if you're interested. Cheers.

prune fails in IE8

The prune method is failing in IE8. Here's my hack-fix that I added to my local copy - but there is probably a more elegant way to address this:

str = _s.chars(str);
for(i in str) {...}
str = str.join('');

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.