esamattis / underscore.string Goto Github PK
View Code? Open in Web Editor NEWString manipulation helpers for javascript
Home Page: http://esamattis.github.com/underscore.string/
String manipulation helpers for javascript
Home Page: http://esamattis.github.com/underscore.string/
Hi,
your website (http://epeli.github.com/underscore.string/) provides two download links:
The production version is still version 1.2.0, however. It looks like the file wasn't updated when 2.0.0 was released.
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!
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!
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
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"]
Have you considered adding indent and dedent to your library?
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 ?
Here's the example: https://gist.github.com/1929469
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?
Might want to consider adding https://github.com/gmosx/inflection to this awesome library... I'd certainly enjoy that.
Which breaks _s.words in the case where _s isn't mixed in to _ or _ isn't in the global scope.
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.
I would expect:
_("Hello").truncate(15) => "Hello"
but instead
_("Hello").truncate(15) => "Hello..."
Could also be configurable if necessary.
Pull request to follow.
When using _('Hello').truncate(10) like in the example, I get the output "Hello..."
Negative parm:
_.chop("some text",-1);
will produce an infinite loop.
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!
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'
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?).
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
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
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?
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('post') // => 'posts'
_.singularize('posts') // => 'post'
or
_.pluralize(1, 'post') //=> 'post'
_.pluralize(2, 'post') //=> 'posts'
_.pluralize(1, 'posts') //=> 'post'
Wondering if you could update your package.json to get rid of this error. Thanks!
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.
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.
just updated with npm to [email protected] and it seems to be missing the index.js file...
What happened to reverseString method in npm module?
Object # has no method 'reverseString'
There seem to be code differences between the v2.0.0 code on github + the documentation compared to what is actually installed using: npm install [email protected]
When i run npm install [email protected] the slugify function does not appear in the underscore.string.js file.
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.
The NPM-hosted version seems to be missing the slugify, toSentence methods.
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...
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:
.toString()
everywhere?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?
hey,
could you add a php-strip_tags-like function? this one works fine for me:
http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
and integration in _s would be nice
Something like this:
_.repeat("foo", 3) // "foofoofoo"
Thanks!
If you log the object you get:
{ VERSION: '1.2.0',
isBlank: [Function],
stripTags: [Function],
...
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
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.
Example:
_.prune('Обикновен текст', 40, "...")
returns:
'...'
this is Bulgarian (meaning 'Regular text')
please :)
Underscore.js is currently on 1.2.1. Can you release a new underscore.string
that references this please (or just bump the dependency to ~1.2), assuming it is still compatible?
_.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;
},
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 ]
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.
Using underscore.string as a mixin causes an issue with _.intersect
- please see underscore issue 443 for details.
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!
This an attempt to fill that cap
cap = gap
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.