string.js
, or simply S
is a lightweight (< 4k 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 clobberPrototype()
.
Here's a list of alternative frameworks:
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
npm install string
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.
Browsers
<script src="https://raw.github.com/jprichardson/string.js/master/lib/string.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/jprichardson/lib/string.js/master/string.min.js"></script>
A global variable window.S
or simply S
is created.
Both
var doesIt = S('my cool string').left(2).endsWith('y');
Access the wrapped string using s
variable or toString()
var name = S('Your name is JP').right(2).s;
is the same as…
var name = S('Your name is JP').right(2).toString();
Still like the clean look of calling these methods directly on native Strings? No problem. Call clobberPrototype()
. 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.clobberPrototype();
var name = 'Your name is JP'.right(2);
S.restorePrototype();
Browser Compatiblity
string.js
has been designed to be compatible with Node.js and with IE6+, Firefox 3+, Safari 2+, Chrome 3+. Please click here to run the tests in your browser. Report any browser issues here: https://github.com/jprichardson/string.js/issues
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));
Methods
See test file 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
S(['a,b']).s
S({hi: 'jp'}).s
- camelize()
Remove any underscores or dashes and convert a string into camel casing.
Example:
S('data_rate').camelize().s;
S('background-color').camelize().s;
S('-moz-something').camelize().s;
S('_car_speed_').camelize().s;
S('yes_we_can').camelize().s;
- capitalize()
Capitalizes the first character of a string.
Example:
S('jon').capitalize().s;
S('JP').capitalize().s;
+ clobberPrototype()
Modifies String.prototype
to have all of the methods found in string.js.
Example:
S.clobberPrototype();
- 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;
- contains(ss)
Returns true if the string contains ss
.
Alias: include()
Example:
S('JavaScript is one of the best languages!').contains('one');
- dasherize()
Returns a converted camel cased string into a string delimited by dashes.
Examples:
S('dataRate').dasherize().s;
S('CarSpeed').dasherize().s;
S('yesWeCan').dasherize().s;
S('backgroundColor').dasherize().s;
- decodeHtmlEntities()
Decodes HTML entities into their string representation.
S('Ken Thompson & Dennis Ritchie').decodeHtmlEntities().s;
S('3 < 4').decodeHtmlEntities().s;
- endsWith(ss)
Returns true if the string ends with ss
.
Example:
S("hello jon").endsWith('jon');
- escapeHTML()
Escapes the html.
Example:
S('<div>hi</div>').escapeHTML().s;
- include(ss)
Returns true if the string contains the ss
.
Alias: contains()
Example:
S('JavaScript is one of the best languages!').include('one');
- isAlpha()
Return true if the string contains only letters.
Example:
S("afaf").isAlpha();
S('fdafaf3').isAlpha();
S('dfdf--dfd').isAlpha();
- isAlphaNumeric()
Return true if the string contains only letters and numbers
Example:
S("afaf35353afaf").isAlphaNumeric();
S("FFFF99fff").isAlphaNumeric();
S("99").isAlphaNumeric();
S("afff").isAlphaNumeric();
S("Infinity").isAlphaNumeric();
S("-Infinity").isAlphaNumeric();
S("-33").isAlphaNumeric();
S("aaff..").isAlphaNumeric();
- isEmpty()
Return true if the string is solely composed of whitespace or is null
/undefined
.
Example:
S(' ').isEmpty();
S('\t\t\t ').isEmpty();
S('\n\n ').isEmpty();
S('helo').isEmpty();
S(null).isEmpty();
S(undefined).isEmpty();
- isLower()
Return true if the character or string is lowercase
Example:
S('a').isLower();
S('z').isLower();
S('B').isLower();
S('hijp').isLower();
S('hi jp').isLower();
S('HelLO').isLower();
- isNumeric()
Return true if the string only contains digits
Example:
S("3").isNumeric();
S("34.22").isNumeric();
S("-22.33").isNumeric();
S("NaN").isNumeric();
S("Infinity").isNumeric();
S("-Infinity").isNumeric();
S("JP").isNumeric();
S("-5").isNumeric();
S("000992424242").isNumeric();
- isUpper()
Returns true if the character or string is uppercase
Example:
S('a').isUpper()
S('z').isUpper()
S('B').isUpper()
S('HIJP').isUpper()
S('HI JP').isUpper()
S('HelLO').isUpper()
- left(n)
Return the substring denoted by n
positive left-most characters.
Example:
S('My name is JP').left(2).s;
S('Hi').left(0).s;
S('My name is JP').left(-2).s;
- length
Property to return the length of the string object.
Example:
S('hi').length;
- lines()
Returns an array of native strings representing lines with whitespace trimmed.
Example:
var lines = S('1 Infinite Loop\r\nCupertino, CA').lines();
lines[0] // '1 Infinite Loop'
lines[1] // 'Cupertino, CA'
- parseCSV()
Parses a CSV line into an array.
Arguments:
delimiter
: The character that is separates or delimits fields. Default: ,
qualifier
: The character that encloses fields. Default: "
Example:
S("'a','b','c'").parseCSV(',', "'")
S('"a","b","c"').parseCSV()
S('a,b,c').parseCSV(',', null)
S("'a,','b','c'").parseCSV(',', "'")
S('"a","b",4,"c"').parseCSV(',', null)
S('"a","b","4","c"').parseCSV()
S('"a","b", "4","c"').parseCSV()
S('"a","b", 4,"c"').parseCSV(",", null)
S('"a","b\\"","d","c"').parseCSV()
- repeat(n)
Returns a string repeated n
times.
Alias: times()
Example:
S(' ').repeat(5).s;
S('*').repeat(3).s;
- replaceAll(ss, newstr)
Return the new string with all occurrences of ss
replaced with newstr
.
Example:
S(' does IT work? ').replaceAll(' ', '_').s;
S('Yes it does!').replaceAll(' ', '').s;
+ restorePrototype()
Restore the original String prototype. Typically used in conjunction with clobberPrototype()
.
Example:
S.restorePrototype();
- right(n)
Return the substring denoted by n
positive right-most characters.
Example:
S('I AM CRAZY').right(2).s;
S('Does it work? ').right(4).s;
S('Hi').right(0).s;
S('My name is JP').right(-2).s;
- s
Alias: toString()
The encapsulated native string representation of an S
object.
Example:
S('my name is JP.').capitalize().s;
var a = "Hello " + S('joe!');
S("Hello").toString() === S("Hello").s;
- slugify()
Converts the text into a valid url slug
S('Global Thermonuclear Warfare').slugify().s
- startsWith(prefix)
Return true if the string starts with prefix
.
Example:
S("JP is a software engineer").startsWith("JP");
S('wants to change the world').startsWith("politicians");
- stripTags([tag1],[tag2],...)
Strip all of the HTML tags or tags specified by the parameters.
Example:
S('<p>just <b>some</b> text</p>').stripTags().s
S('<p>just <b>some</b> text</p>').stripTags('p').s
- times(n)
Returns a string repeated n
times.
Alias: repeat()
Example:
S(' ').times(5).s
S('*').times(3).s
- toCSV(options)
Converts an array or object to a CSV line.
You can either optionally pass in two string arguments or pass in a configuration object.
String Arguments:
delimiter
: The character that is separates or delimits fields. Default: ,
qualifier
: The character that encloses fields. Default: "
Object Configuration:
delimiter
: The character that is separates or delimits fields. Default: ,
qualifier
: The character that encloses fields. Default: "
escape
: The character that escapes any incline qualifier
characters. Default: \
, in JS this is \\
encloseNumbers
: Enclose number objects with the qualifier
chracter. Default: true
keys
: If the input isn't an array, but an object, then if this is set to true, the keys will be output to the CSV line, otherwise it's the object's values. Default: false
.
Example:
S(['a', 'b', 'c']).toCSV().s
S(['a', 'b', 'c']).toCSV(':').s
S(['a', 'b', 'c']).toCSV(':', null).s
S(['a', 'b', 'c']).toCSV('*', "'").s
S(['a"', 'b', 4, 'c']).toCSV({delimiter: ',', qualifier: '"', escape: '\\', encloseNumbers: false}).s
S({firstName: 'JP', lastName: 'Richardson'}).toCSV({keys: true}).s
S({firstName: 'JP', lastName: 'Richardson'}).toCSV().s
- toInt()
Return the number value in integer form. Wrapper for parseInt()
. Can also parse hex values.
Example:
S('5').toInt();
S('5.3').toInt();
S(5.3).toInt();
S('-10').toInt();
S('55 adfafaf').toInt();
S('afff 44').toInt();
S('0xff').toInt()
- toFloat([precision])
Return the float value, wraps parseFloat.
Example:
S('5').toFloat()
S('5.3').toFloat()
S(5.3).toFloat()
S('-10').toFloat()
S('55.3 adfafaf').toFloat()
S('afff 44').toFloat()
S(3.45522222333232).toFloat(2)
- toString()
Alias: s
Return the string representation of an S
object. Not really necessary to use. However, JS engines will look at an object and display its toString()
result.
Example:
S('my name is JP.').capitalize().toString();
var a = "Hello " + S('joe!');
S("Hello").toString() === S("Hello").s;
- trim()
Return the string with leading and trailing whitespace removed. Reverts to native trim()
if it exists.
Example:
S('hello ').trim().s;
S(' hello ').trim().s;
S('\nhello').trim().s;
S('\nhello\r\n').trim().s;
S('\thello\t').trim().s;
- trimLeft()
Return the string with leading and whitespace removed
Example:
S(' How are you?').trimLeft().s;
- trimRight()
Return the string with trailing whitespace removed.
Example:
S('How are you? ').trimRight().s;
- truncate(length, [chars])
Truncates the string, accounting for word placement and character count.
Example:
S('this is some long text').truncate(3).s
S('this is some long text').truncate(7).s
S('this is some long text').truncate(11).s
S('this is some long text').truncate(12).s
S('this is some long text').truncate(11).s
S('this is some long text').truncate(14, ' read more').s
- underscore()
Returns converted camel cased string into a string delimited by underscores.
Example:
S('dataRate').underscore().s;
S('CarSpeed').underscore().s;
S('yesWeCan').underscore().s;
- unescapeHTML()
Unescapes the html.
Example:
S('<div>hi</div>').unescapeHTML().s;
+ VERSION
Returns native JavaScript string containing the version of string.js
.
Example:
S.VERSION;
Quirks
decodeHtmlEntities()
converts
to 0xa0 (160) and not 0x10 (20). Most browsers consider 0xa0 to be whitespace characters, Internet Explorer does not despite it being part of the ECMA standard. Google Closure does a good job of normalizing this behavior. This may need to fixed in string.js
at some point in time.
Testing
Node.js
Install the dev dependencies:
$ npm install string --development
Then navigate to the installed directory:
$ cd node_modules/string/
Run test package:
$ mocha test
Browser
Click here to run the tests in your web browser.
Credits
I have looked at the code by the creators in the libraries mentioned in Motivation. As noted in the source code, I've specifically used code from Google Closure (Google Inc), Underscore String Esa-Matti Suuronen, and php.js (http://phpjs.org/authors/index).
Author
string.js
was written by JP Richardson. You should follow him on Twitter @jprichardson. Also read his coding blog Procbits. If you write software with others, you should checkout Gitpilot to make collaboration with Git simple.
License
Licensed under MIT.
Copyright (C) 2012 JP Richardson jprichardson@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.