• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jprichardson/string.js: Extra JavaScript string methods.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

jprichardson/string.js

开源软件地址:

https://github.com/jprichardson/string.js

开源编程语言:

JavaScript 100.0%

开源软件介绍:

string.js

build status CDNJS

Sauce Test Status

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:

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

  1. If you want to use this library, you first need to install the [Node.js] (https://nodejs.org/en/).

  2. When you install node.js, will also be installed [npm] (https://www.npmjs.com/).

  3. 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 to run the tests in your browser. Report any browser issues here: https://github.com/jprichardson/string.js/issues

Extending string.js

See: #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 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 &amp; Dennis Ritchie').decodeHTMLEntities().s; //'Ken Thompson & Dennis Ritchie'
S('3 &lt; 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; //&lt;div&gt;hi&lt;/div&gt;

+ 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 string method_id').humanize().s //'The humanize id string method'
S('the  humanize string method  ').humanize().s //'The humanize string method'
S('   capitalize dash-CamelCase_underscore trim  ').humanize().s //'Capitalize dash camel case underscore trim'

- include(ss)

Returns true if the string contains the ss.

Alias: contains()

Example:

S('JavaScript is one of the best languages!').include('one'); //true

- isAlpha()

Return true if the string contains only letters.

Example:

S("afaf").isAlpha(); //true
S('fdafaf3').isAlpha(); //false
S('dfdf--dfd').isAlpha(); //false

- isAlphaNumeric()

Return true if the string contains only letters and numbers

Example:

S("afaf35353afaf").isAlphaNumeric(); //true
S("FFFF99fff").isAlphaNumeric(); //true
S(
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap