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
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
考虑到函数的可用性,要使用 Underscore.string 需要使用 Underscore.js 中的 mixin 函数方式来扩展:
_.mixin(_.string.exports());
否则将可通过 _.string 或 _.str 对象,例如:
_.str.capitalize('epeli')
=> "Epeli"
numberFormat _.numberFormat(number, [ decimals=0, decimalSeparator='.', orderSeparator=','])
格式化数字.
_.numberFormat(1000, 2)
=> "1,000.00"
_.numberFormat(123456789.123, 5, '.', ',')
=> "123,456,789.12300"
levenshtein _.levenshtein(string1, string2)
计算两个字符串之间的Levenshtein distance(字符串相似度算法) .
_.levenshtein('kitten', 'kittah')
=> 2
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']
swapCase _.swapCase(str)
返回一个字符串拷贝,交换字符串文本的大小写。
_.swapCase('hELLO')
=> 'Hello'
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://[email protected]/edtsech/underscore.strings').splice(30, 7, 'epeli')
=> 'https://[email protected]/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=/\s+/)
Split string by delimiter (String or RegExp), /\s+/ by default.
_.words(" I love you ")
=> ["I","love","you"]
_.words("I_love_you", "_")
=> ["I","love","you"]
_.words("I-love-you", /-/)
=> ["I","love","you"]
_.words(" ")
=> []
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';
toSentenceSerial _.toSentenceSerial(array, [delimiter, lastDelimiter])
类似于 toSentence
, 但是使用Serial comma(序列逗号)作为分隔符.
_.toSentenceSerial(['jQuery', 'Mootools'])
=> 'jQuery and Mootools';
_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'])
=> 'jQuery, Mootools, and Prototype'
_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ');
=> 'jQuery, Mootools, unt Prototype';
repeat _.repeat(string, count, [separator])
重复一个字符串 count(参数) 次.
_.repeat("foo", 3)
=> 'foofoofoo';
_.repeat("foo", 3, "bar")
=> 'foobarfoobarfoo'
surround _.surround(string, wrap)
用一个字符串首尾包裹另一个字符串
_.surround("foo", "ab")
=> 'abfooab';
quote _.quote(string) or _.q(string)
把一个字符串用引号引起来。
_.quote('foo')
=> '"foo"';
slugify _.slugify(string)
转换文本成一个URL连体字符串.替换空格,重点符,用破折号和特殊字符。
_.slugify("Un éléphant à l'orée du bois")
=> 'un-elephant-a-loree-du-bois';
注意:此功能依赖字符集
Any suggestions or bug reports are welcome. Just email me or more preferably open an issue.
numberformat
methodlevenshtein
method (Levenshtein distance calculation)swapCase
methodwords
methodtoSentenceSerial
methodsurround
and quote
methods我们从_.string
移除了include
and reverse
两个方法 :
_('foobar').include('bar')
但是,如果您需要此功能,您可以创建别名防止冲突:
_.mixin({
includeString: _.str.include,
reverseString: _.str.reverse
})
// Now wrapper calls and chaining are available.
_('foobar').chain().reverseString().includeString('rab').value()
如果您没有和Underscore.js一起使用 Underscore.string。你可以使用 _.string
为 Underscore.string创建命名空间 ;也可以用 _.string
重新分配_
变量;
_ = _.string
升级到此版本,你需要将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.
Otherwise changes will be rejected.
The MIT License
Copyright (c) 2011 Esa-Matti Suuronen [email protected]
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.