String.js
Extra JavaScript string methods.
Install / Use
/learn @jprichardson/String.jsREADME
string.js
string.js, or simply S is a lightweight (< 5 kb minified and gzipped) JavaScript library for the browser or for Node.js that provides extra String methods. Originally, it modified the String prototype. But I quickly learned that in JavaScript, this is considered poor practice.
Why?
Personally, I prefer the cleanliness of the way code looks when it appears to be native methods. i.e. when you modify native JavaScript prototypes. However, if any app dependency required string.js, then the app's string prototype would be modified in every module. This could be troublesome. So I settled on creating a wrapper a la jQuery style. For those of you prototype hatin' fools, there is the method extendPrototype().
Here's a list of alternative frameworks:
- Prototype Framework's String library
- Uize.String
- Google Closure's String
- Underscore.string
- Sugar.js
- php.js
Why wasn't I happy with any of them? They are all static methods that don't seem to support chaining in a clean way 'OR' they have an odd dependency. Sugar is the notable exception.
Installation
-
If you want to use this library, you first need to install the [Node.js] (https://nodejs.org/en/).
-
When you install node.js, will also be installed [npm] (https://www.npmjs.com/).
-
Please run the following command.
npm install --save string
Experiment with String.js Now
Assuming you're on http://stringjs.com, just simply open up the Webkit inspector in either Chrome or Safari, or the web console in Firefox and you'll notice that string.js is included in this page so that you can start experimenting with it right away.
Usage
Node.js
var S = require('string');
Originally, I was using $s but glancing over the code, it was easy to confuse $s for string.js with $ for jQuery. Feel free to use the most convenient variable for you.
Rails
Checkout this gem to easily use string.js on the asset pipeline: https://github.com/jesjos/stringjs-rails
Browsers
<!-- HTML5 -->
<script src="https://cdn.rawgit.com/jprichardson/string.js/master/dist/string.min.js"></script>
<!-- Note that in the mime type for Javascript is now officially 'application/javascript'. If you
set the type to application/javascript in IE browsers, your Javacript will fail. Just don't set a
type via the script tag and set the mime type from your server. Most browsers look at the server mime
type anyway -->
<!-- For HTML4/IE -->
<script type="text/javascript" src="https://cdn.rawgit.com/jprichardson/string.js/master/dist/string.min.js"></script>
A global variable window.S or simply S is created.
AMD Support
It now has AMD support. See require.js on how to use with AMD modules.
Both
var doesIt = S('my cool string').left(2).endsWith('y'); //true
Access the wrapped string using s variable or toString()
var name = S('Your name is JP').right(2).s; //'JP'
is the same as…
var name = S('Your name is JP').right(2).toString(); //'JP'
Still like the clean look of calling these methods directly on native Strings? No problem. Call extendPrototype(). Make sure to not call this at the module level, at it'll effect the entire application lifecycle. You should really only use this at the method level. The one exception being if your application will not be a dependency of another application.
S.extendPrototype();
var name = 'Your name is JP'.right(2); //'JP'
S.restorePrototype(); //be a good citizen and clean up
Browser Compatibility
string.js has been designed to be compatible with Node.js and with IE6+, Firefox 3+, Safari 2+, Chrome 3+. Please [click here][browsertest] to run the tests in your browser. Report any browser issues here: https://github.com/jprichardson/string.js/issues
Extending string.js
See: https://github.com/jprichardson/string.js/pull/57
Native JavaScript Methods
string.js imports all of the native JavaScript methods. This is for convenience. The only difference is that the imported methods return string.js objects instead of native JavaScript strings. The one exception to this is the method charAt(index). This is because charAt() only returns a string of length one. This is typically done for comparisons and a string.js object will have little to no value here.
All of the native methods support chaining with the string.js methods.
Example:
var S = require('string');
var phrase = S('JavaScript is the best scripting language ever!');
var sub = 'best scripting';
var pos = phrase.indexOf(sub);
console.log(phrase.substr(pos, sub.length).truncate(8)); //best...
Methods
See [test file][testfile] for more details.
I use the same nomenclature as Objective-C regarding methods. + means static or class method. - means non-static or instance method.
- constructor(nativeJsString)
This creates a new string.js object. The parameter can be anything. The toString() method will be called on any objects. Some native objects are used in some functions such as toCSV().
Example:
S('hello').s //"hello"
S(['a,b']).s //"a,b"
S({hi: 'jp'}).s //"[object Object]""
- between(left, right)
Extracts a string between left and right strings.
Example:
S('<a>foo</a>').between('<a>', '</a>').s // => 'foo'
S('<a>foo</a></a>').between('<a>', '</a>').s // => 'foo'
S('<a><a>foo</a></a>').between('<a>', '</a>').s // => '<a>foo'
S('<a>foo').between('<a>', '</a>').s // => ''
S('Some strings } are very {weird}, dont you think?').between('{', '}').s // => 'weird'
S('This is a test string').between('test').s // => ' string'
S('This is a test string').between('', 'test').s // => 'This is a '
- camelize()
Remove any underscores or dashes and convert a string into camel casing.
Example:
S('data_rate').camelize().s; //'dataRate'
S('background-color').camelize().s; //'backgroundColor'
S('-moz-something').camelize().s; //'MozSomething'
S('_car_speed_').camelize().s; //'CarSpeed'
S('yes_we_can').camelize().s; //'yesWeCan'
- capitalize()
Capitalizes the first character of a string.
Example:
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
- chompLeft(prefix)
Removes prefix from start of string.
Example:
S('foobar').chompLeft('foo').s; //'bar'
S('foobar').chompLeft('bar').s; //'foobar'
- chompRight(suffix)
Removes suffix from end of string.
Example:
S('foobar').chompRight('bar').s; //'foo'
S('foobar').chompRight('foo').s; //'foobar'
- collapseWhitespace()
Converts all adjacent whitespace characters to a single space.
Example:
var str = S(' String \t libraries are \n\n\t fun\n! ').collapseWhitespace().s; //'String libraries are fun !'
- contains(ss)
Returns true if the string contains ss.
Alias: include()
Example:
S('JavaScript is one of the best languages!').contains('one'); //true
- count(substring)
Returns the count of the number of occurrences of the substring.
Example:
S('JP likes to program. JP does not play in the NBA.').count("JP")// 2
S('Does not exist.').count("Flying Spaghetti Monster") //0
S('Does not exist.').count("Bigfoot") //0
S('JavaScript is fun, therefore Node.js is fun').count("fun") //2
S('funfunfun').count("fun") //3
- dasherize()
Returns a converted camel cased string into a string delimited by dashes.
Examples:
S('dataRate').dasherize().s; //'data-rate'
S('CarSpeed').dasherize().s; //'-car-speed'
S('yesWeCan').dasherize().s; //'yes-we-can'
S('backgroundColor').dasherize().s; //'background-color'
- decodeHTMLEntities()
Decodes HTML entities into their string representation.
S('Ken Thompson & Dennis Ritchie').decodeHTMLEntities().s; //'Ken Thompson & Dennis Ritchie'
S('3 < 4').decodeHTMLEntities().s; //'3 < 4'
- endsWith(ss)
Returns true if the string ends with ss.
Example:
S("hello jon").endsWith('jon'); //true
- escapeHTML()
Escapes the html.
Example:
S('<div>hi</div>').escapeHTML().s; //<div>hi</div>
+ extendPrototype()
Modifies String.prototype to have all of the methods found in string.js.
Example:
S.extendPrototype();
- ensureLeft(prefix)
Ensures string starts with prefix.
Example:
S('subdir').ensureLeft('/').s; //'/subdir'
S('/subdir').ensureLeft('/').s; //'/subdir'
- ensureRight(suffix)
Ensures string ends with suffix.
Example:
S('dir').ensureRight('/').s; //'dir/'
S('dir/').ensureRight('/').s; //'dir/'
- humanize()
Transforms the input into a human friendly form.
Example:
S('the_humanize_string_method').humanize().s //'The humanize string method'
S('ThehumanizeStringMethod').humanize().s //'Thehumanize string method'
S('the humanize string method').humanize().s //'The humanize string method'
S('the humanize_id st

