Underscore.string.js Version (2.0.0) 中文文档
Javascript缺乏完整的字符串操作。Underscore.string.js试图填补这一空白。您可以在深入 JavaScript 中找到生成中方法列表
正如名称指出的Underscore.string.js为 Underscore.js 的扩展,但你可以独立使用_s-全局变量。但配合 Underscore.js 使用,您可以使用面向对象的样式和链式调用:
_(" epeli ").chain().trim().capitalize().value()
=> "Epeli"
github项目地址:http://epeli.github.com/underscore.string/ | https://github.com/epeli/underscore.string
Node.js 安装
npm package
npm install underscore.string
Standalone usage:
var _s = require('underscore.string');
Integrate with Underscore.js:
var _ = require('underscore');
// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)
_.str = require('underscore.string');
// Mix in non-conflict functions to Underscore namespace if you want
_.mixin(_.str.exports());
// All functions, include conflict, will be available through _.str object
_.str.include('Underscore.string', 'string'); // => true
String 函数
考虑到函数的可用性,要使用 Underscore.string 需要使用 Underscore.js 中的 mixin 函数方式来扩展:
_.mixin(_.string.exports());
否则将可通过 _.string 或 _.str 对象,例如:
_.str.capitalize('epeli')
=> "Epeli"
capitalize _.capitalize(string)
将字符串的第一个字母转换为大写。(译者注:在中国这个方法貌似没什么大的用处)
_.capitalize("epeli")
=> "Epeli"
chop _.chop(string, step)
根据step参数切割字符串,并转化成数组
_.chop('whitespace', 3)
=> ['whi','tes','pac','e']
clean _.clean(str)
压缩一些空格为一个空格。(译者注:去首位空格)
_.clean(" foo bar ")
=> 'foo bar'
chars _.chars(str)
将字符串转换为数组。(译者注:去首位空格)
_.chars('Hello')
=> ['H','e','l','l','o']
includes _.includes(string, substring)
测试字符串中包含一个子字符串
_.includes("foobar", "ob")
=> true
include 只有通过_.str对象使用这个方法,因为Underscore.js已具有相同名称的函数。
_.str.include("foobar", "ob")
=> true
includes 函数已经被移除
但是如果你与以前版本的兼容性,可以以这种方式创建:
_.includes = _.str.include
count _.count(string, substring)
返回substring字符串在字符中第一次出现的所引值:
_('Hello world').count('l')
=> 3
escapeHTML _.escapeHTML(string)
将HTML特殊字符转换成等值的实体。
_('<div>Blah blah blah</div>').escapeHTML();
=> '<div>Blah blah blah</div>'
unescapeHTML _.unescapeHTML(string)
实体字符转换为等值的HTML。
_('<div>Blah blah blah</div>').unescapeHTML();
=> '<div>Blah blah blah</div>'
insert _.insert(string, index, substing)
在字符串的指定索引值(index参数)上插入另一个字符串(substing参数)
_('Hello ').insert(6, 'world')
=> 'Hello world'
isBlank _.isBlank(string)
判断是否为 可视为空字符串,例如'\n'是换行,在页面不会呈现
_('').isBlank(); // => true
_('\n').isBlank(); // => true
_(' ').isBlank(); // => true
_('a').isBlank(); // => false
join _.join(separator, *strings)
根据给定的分隔符(separator参数)拼接给定的字符串,*strings参数,表示可为多个字符串
_.join(" ", "foo", "bar")
=> "foo bar"
lines _.lines(str)
根据换行切割字符串,并转换为数组
_.lines("Hello\nWorld")
=> ["Hello", "World"]
reverse 只有通过_.str对象使用这个方法,因为Underscore.js已具有相同名称的函数。
返回颠倒的字符串:
_.str.reverse("foobar")
=> 'raboof'
splice _.splice(string, index, howmany, substring)
就像一个数组(splice).
_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli')
=> 'https://edtsech@bitbucket.org/epeli/underscore.strings'
startsWith _.startsWith(string, starts)
此方法检查字符串是以给定的字符串(starts参数)开始。
_("image.gif").startsWith("image")
=> true
endsWith _.endsWith(string, ends)
此方法检查字符串是以给定的字符串(ends参数)结束。
_("image.gif").endsWith("gif")
=> true
succ _.succ(str)
返回给定字符串的下一个字符。
_('a').succ()
=> 'b'
_('A').succ()
=> 'B'
supplant
Supplant 被移除, 请使用 Underscore.js template function.
strip trim的别名
lstrip ltrim的别名
rstrip rtrim的别名
titleize _.titleize(string)
将每个单词的首字母转换为大写
_('my name is epeli').titleize()
=> 'My Name Is Epeli'
camelize _.camelize(string)
将下划线或者中划线字符 转换转换成 camelized ,原文:Converts underscored or dasherized string to a camelized one
_('-moz-transform').camelize()
=> 'MozTransform'
underscored _.underscored(string)
将camelized或者中划线转化成下划线,原文:Converts a camelized or dasherized string into an underscored one
_('MozTransform').underscored()
=> 'moz_transform'
dasherize _.dasherize(string)
将camelized或者下划线转化成中划线,原文:Converts a underscored or camelized string into an dasherized one
_('MozTransform').dasherize()
=> '-moz-transform'
humanize _.humanize(string)
将下划线, camelized ,或中划线字符串转换成一个人性化字符串。还删除开始和结束的空白,并删除后缀“ _id ” 。
原文:Converts an underscored, camelized, or dasherized string into a humanized one.
Also removes beginning and ending whitespace, and removes the postfix '_id'.
_(' capitalize dash-CamelCase_underscore trim ').humanize()
=> 'Capitalize dash camel case underscore trim'
trim _.trim(string, [characters])
根据给定的字符串(characters参数)从开始和结束的地方裁剪字符串。默认为空格字符,既去首位空格。
_.trim(" foobar ")
=> "foobar"
_.trim("_-foobar-_", "_-")
=> "foobar"
ltrim _.ltrim(string, [characters])
左裁剪. 与trim相似,但仅限于左侧。
rtrim _.rtrim(string, [characters])
右裁剪. 与trim相似,但仅限于右侧。
truncate _.truncate(string, length, truncateString)
根据给定的截断长度(length参数)和截断字符(truncateString参数)截断字符
_('Hello world').truncate(5)
=> 'Hello...'
_('Hello').truncate(10)
=> 'Hello'
prune _.prune(string, length, pruneString)
优雅的截断的版本。确保已修剪的字符串不会超过原始长度。 截断时,避免单词被截断。
_('Hello, world').prune(5)
=> 'Hello...'
_('Hello, world').prune(8)
=> 'Hello...'
_('Hello, world').prune(5, ' (read a lot more)')
=> 'Hello, world' (as adding "(read a lot more)" would be longer than the original string)
_('Hello, cruel world').prune(15)
=> 'Hello, cruel...'
_('Hello').prune(10)
=> 'Hello'
words _.words(str, delimiter=" ")
根据分隔符(字符串 或者 正则表达式)拆分字符串, 默认为'' .
_.words("I love you")
=> ["I","love","you"]
_.words("I_love_you", "_")
=> ["I","love","you"]
_.words("I-love-you", /-/)
=> ["I","love","you"]
sprintf _.sprintf(string format, *arguments)
C like string formatting.
Credits goes to Alexandru Marasteanu.
有关更详细的文档, 更多查看 原始页面.
_.sprintf("%.1f", 1.17)
"1.2"
pad _.pad(str, length, [padStr, type])
用字符填充字符串(str
参数)直到该字符串长度等于给定的长度( length
参数)。默认情况下,填充从用空字符(" "
)在字符串左边( left)填充。如有必要,padStr
参数是截断到单个字符。
_.pad("1", 8)
-> " 1";
_.pad("1", 8, '0')
-> "00000001";
_.pad("1", 8, '0', 'right')
-> "10000000";
_.pad("1", 8, '0', 'both')
-> "00001000";
_.pad("1", 8, 'bleepblorp', 'both')
-> "bbbb1bbb";
lpad _.lpad(str, length, [padStr])
左填充一个字符串. pad(str, length, padStr, 'left')
的简写
_.lpad("1", 8, '0')
-> "00000001";
rpad _.rpad(str, length, [padStr])
右填充一个字符串. pad(str, length, padStr, 'right')
的简写
_.rpad("1", 8, '0')
-> "10000000";
lrpad _.lrpad(str, length, [padStr])
左右两边填充一个字符串. pad(str, length, padStr, 'both')
的简写
_.lrpad("1", 8, '0')
-> "00001000";
center lrpad的别名
ljust lpad的别名
rjust rpad的别名
toNumber _.toNumber(string, [decimals])
将字符串解析为数字.如果字符串不能转换为数字将返回NaN
_('2.556').toNumber()
=> 3
_('2.556').toNumber(1)
=> 2.6
strRight _.strRight(string, pattern)
从左到右的模式检索字符串中的给定的子字符串(pattern参数),并返回子字符串开始的右侧字符串,如果找不到匹配的模式就返回所有字符串。
_('This_is_a_test_string').strRight('_')
=> "is_a_test_string";
strRightBack _.strRightBack(string, pattern)
从右到左的模式检索字符串中的给定的子字符串(pattern参数),,并返回子字符串开始的右侧字符串,如果找不到匹配的模式就返回所有字符串。
_('This_is_a_test_string').strRightBack('_')
=> "string";
strLeft _.strLeft(string, pattern)
从左到右的模式检索字符串中的给定的子字符串(pattern参数),并返回子字符串开始的左侧字符串,如果找不到匹配的模式就返回所有字符串。
_('This_is_a_test_string').strLeft('_')
=> "This";
strLeftBack _.strLeftBack(string, pattern)
从右到左的模式检索字符串中的给定的子字符串(pattern参数),,并返回子字符串开始的左侧字符串,如果找不到匹配的模式就返回所有字符串。
_('This_is_a_test_string').strLeftBack('_')
=> "This_is_a_test";
stripTags
从字符串中移除所有的html标签
_('a <a href="#">link</a>').stripTags()
=> 'a link'
_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
toSentence _.toSentence(array, [delimiter, lastDelimiter])
联接一个数组转换成人类可以读懂的句子.
_.toSentence(['jQuery', 'Mootools', 'Prototype'])
=> 'jQuery, Mootools and Prototype';
_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ')
=> 'jQuery, Mootools unt Prototype';
Roadmap
Any suggestions or bug reports are welcome. Just email me or more preferably open an issue.
Changelog
2.0.0
- Added prune, humanize functions
- Added .string (.str) namespace for Underscore.string library
- Removed includes function
Problems
我们从_.string
移除了include
and reverse
两个方法 :
- 这样调用不被支持了:
_('foobar').include('bar')
- Chaining isn't available too.
但是,如果您需要此功能,您可以创建别名防止冲突:
_.mixin({
includeString: _.str.include,
reverseString: _.str.reverse
})
// Now wrapper calls and chaining are available.
_('foobar').chain().reverseString().includeString('rab').value()
Standalone Usage
如果您没有和Underscore.js一起使用 Underscore.string。你可以使用 _.string
为 Underscore.string创建命名空间 ;也可以用 _.string
重新分配_
变量;
_ = _.string
Upgrade
升级到此版本,你需要将Underscore.string扩充到Underscore对象:
_.mixin(_.string.exports());
and all non-conflict Underscore.string functions will be available through Underscore object.
Also function includes
has been removed, you should replace this function by _.str.include
or create alias _.includes = _.str.include
and all your code will work fine.
1.1.6
- Fixed reverse and truncate
- Added isBlank, stripTags, inlude(alias for includes)
- Added uglifier compression
1.1.5
- Added strRight, strRightBack, strLeft, strLeftBack
1.1.4
- Added pad, lpad, rpad, lrpad methods and aliases center, ljust, rjust
- Integration with Underscore 1.1.6
1.1.3
- Added methods: underscored, camelize, dasherize
- Support newer version of npm
1.1.2
- Created functions: lines, chars, words functions
1.0.2
- Created integration test suite with underscore.js 1.1.4 (now it's absolutely compatible)
- Removed 'reverse' function, because this function override underscore.js 'reverse'
Contribute
- Fork & pull request. Don't forget about tests.
- If you planning add some feature please create issue before.
Otherwise changes will be rejected.
Contributors list
- Esa-Matti Suuronen esa-matti@suuronen.org (http://esa-matti.suuronen.org/),
- Edward Tsech edtsech@gmail.com,
- Sasha Koss kossnocorp@gmail.com (http://koss.nocorp.me/),
- Vladimir Dronnikov dronnikov@gmail.com,
- Pete Kruckenberg (https://github.com/kruckenb),
- Paul Chavard paul@chavard.net (http://tchak.net),
- Ed Finkler coj@funkatron.com (http://funkatron.com)
- Pavel Pravosud rwz@duckroll.ru
- Anton Lindqvist anton@qvister.se (http://qvister.se)