Underscore.string.js が便利そうなので紹介します. JavaScript のちょっと面倒な文字列処理を Ruby や Python っぽくいい感じにやってくれます.
使い方
サーバで使う
npm からインストール
npm install underscore.string
単体で使う:
var _s = require('underscore.string');
Underscore.js と使う:
var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');
クライアントで使う
bower からインストール
bower install underscore.string
単体で使う:
underscore.string.js
を html に読み込む.
Underscore.js と使う:
underscore.js
と underscore.string.js
を html に読み込み任意のファイルに以下を追記する.
_.mixin(_.str.exports());
便利そうなメソッド紹介
数字の整形 _.numberFormat(number, [ decimals=0, decimalSeparator='.', orderSeparator=','])
_.numberFormat(1000, 2)
=> "1,000.00"
_.numberFormat(123456789.123, 5, '.', ',')
=> "123,456,789.12300"
文字列を任意の数で分割し配列化 _.chop(string, step)
_.chop('whitespace', 3)
=> ['whi','tes','pac','e']
文字列を 1 文字づつに分割し配列化 _.chars(str)
_.chars('Hello')
=> ['H','e','l','l','o']
文字列に任意の文字が含まれるかチェック available only through
_.str.include("foobar", "ob")
=> true
文字列の何文字目に任意の文字が含まれるかチェック _.count(string, substring)
_('Hello world').count('l')
=> 3
HTML の特殊文字を変換する _.escapeHTML(string)
_('<div>Blah blah blah</div>').escapeHTML();
=> '<div>Blah blah blah</div>'
変換された HTML の特殊文字を元に戻す _.unescapeHTML(string)
_('<div>Blah blah blah</div>').unescapeHTML();
=> '<div>Blah blah blah</div>'
文字列の任意の箇所に指定の文字列を挿入する _.insert(string, index, substing)
_('Hello ').insert(6, 'world')
=> 'Hello world'
空白をチェック _.isBlank(string)
_('').isBlank(); // => true
_('\n').isBlank(); // => true
_(' ').isBlank(); // => true
_('a').isBlank(); // => false
文字列の結合 _.join(separator, *strings)
_.join(" ", "foo", "bar")
=> "foo bar"
文字列の先頭のアサート _.startsWith(string, starts)
_("image.gif").startsWith("image")
=> true
文字列の末尾のアサート _.endsWith(string, ends)
_("image.gif").endsWith("gif")
=> true
キャメルケース化 _.camelize(string)
_('moz-transform').camelize()
=> 'mozTransform'
_('-moz-transform').camelize()
=> 'MozTransform'
パスカルケース化 _.classify(string)
_('some_class_name').classify()
=> 'SomeClassName'
スネークケース化 _.underscored(string)
_('MozTransform').underscored()
=> 'moz_transform'
任意の文字数を切り捨てる _.truncate(string, length, truncateString)
_('Hello world').truncate(5)
=> 'Hello...'
_('Hello').truncate(10)
=> 'Hello'
任意の桁数にゼロパディング _.lpad(str, length, [padStr])
_.lpad("1", 8, '0')
-> "00000001";
文字型の数字を任意の小数点で数値型に変換 _.toNumber(string, [decimals])
_('2.556').toNumber()
=> 3
_('2.556').toNumber(1)
=> 2.6
任意の文字列をくり返す _.repeat(string, count, [separator])
_.repeat("foo", 3)
=> 'foofoofoo';
_.repeat("foo", 3, "bar")
=> 'foobarfoobarfoo'
ではでは楽しい JavaScript ライフを(・.・)ノ