Dive Into Prototype.js(2)--Stringオブジェクト

blank( )

文字列は空かスペースだけかをチェックし、True/Falseで返す。

>>> var str = "a";
>>> str.blank();
false
>>> str=" ";
" "
>>> str.blank();
true
camelize( )

ハイフンで繋いだ文字列をCamel形式に変換する。
(Prototype内部でこのメソッドを使用して、CSSプロパティからDOMスタイルプロパティに変換している。)

>>> '-background-color-'.camelize();
"BackgroundColor"
capitalize( )

文字列の頭文字のみ大文字にし、残りは小文字にする。

>>> 'HELLO WORLD!'.capitalize();
"Hello world!"
dasherize( )

アンダーラインをハイフンで置換する。

>>> '_border_bottom_width_'.dasherize();
"-border-bottom-width-"

注:underscore()と一緒に使用することで、DOMスタイルプロパティからCSSプロパティに変換可能。

>>> 'borderBottomWidth'.underscore().dasherize();
"border-bottom-width"
empty( )

文字列は空かをチェックする。

''.empty();
//-> true
'  '.empty();
//-> false
endsWith(substring)

文字列の末尾に指定された文字列があるか判定する。

>>> 'test'.endsWith('st');
true
startsWith(substring)

(上記参照)

escapeHTML( )

文字列でのHTMLタグをエスケープする。

>>> '<div class="article">This is an article</div>'.escapeHTML();
"&lt;div class="article"&gt;This is an article&lt;/div&gt;"
evalJSON( [sanitize = false] )

JSONjavascriptオブジェクトに変換する。

>>> var person = '{ "name": "Violet", "occupation": "character" }'.evalJSON();
>>> person
Object name=Violet occupation=character
>>> person.name;
"Violet"

注:パラメータsanitizeがTrueにすることで、文字列が悪意であるかをチェックする。

evalScripts( )

文字列のScriptを評価し、結果を配列で戻る。

>>> '<script>2 + 2</script><script>alert("hello world!")</script>'.evalScripts();
[4, undefined]
// 2+2の結果を計算し、ポップアップでhello worldを表示する。
extractScripts( )

文字列のScriptを配列に解析する

'<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts();
// -> ['2 + 2', 'alert("hello world!")']

注:解析した配列を使用する場合、下記の方法で使用可能

var myScripts = '<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts();
// -> ['2 + 2', 'alert("hello world!")']

var myReturnedValues = myScripts.map(function(script) {
  return eval(script);
});a
// -> [4, undefined] (2+2の結果を計算し、ポップアップでhello worldを表示する。)
gsub(pattern, replacement)

固定文字列や正規表現パターンで、文字列の検索・置換を行うだけでなく、置換処理に際してさらに制御可能。

var mouseEvents = 'click dblclick mousedown mouseup mouseover mousemove mouseout';
mouseEvents.gsub(' ', ', ');
// -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout'
mouseEvents.gsub(/\s+/, ', ');
// -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout'

二つ目のパラメータは置換文字列となるが、関数を渡した場合マッチした度に呼ばれる

var markdown = '![a pear](/img/pear.jpg) ![an orange](/img/orange.jpg)';
markdown.gsub(/!\[(.*?)\]\((.*?)\)/, function(match){
  return '<img alt="' + match[1] + '" src="' + match[2] + '" />';
});
// -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />'

テンプレートとしての使用法もある。

markdown.gsub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />');
// -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />'

注:正規表現で「g」を使用しないで下さい。無限ループになる可能性があります。

include(substring)

文字列の中で含まれているかを判定する。

'Prototype framework'.include('frame');
//-> true
inspect([useDoubleQuotes = false])

debug向けの文字列を返す。パラメータTrueを渡した場合文字列の中のクォートをエスケープしなくなる。

'I\'m so happy.'.inspect();
// -> '\'I\\\'m so happy.\'' (displayed as 'I\'m so happy.' in an alert dialog or the console)
'I\'m so happy.'.inspect(true);
// -> '"I'm so happy."'  (displayed as "I'm so happy." in an alert dialog or the console)
interpolate(object[, pattern])

文字列をテンプレートとして使用する。

>>> "#{animals} on a #{transport}".interpolate({ animals: "Pigs", transport: "Surfboard" });
"Pigs on a Surfboard"

var pattern= /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/; 
// '<%= field %>'形式をマッチする
var html = '<div>Name: <b><%= name %></b>, Age: <b><%=age%></b></div>';
var data = { name: 'John Smith', age: 26 };
html.interpolate(data, pattern);
//-> "<div>Name: <b>John Smith</b>, Age: <b>26</b></div>"
isJSON( )

文字列がJSONに適してるかを正規表現で判定する。

"{ foo: 42 }".isJSON()
// -> false
"{ \"foo\": 42 }".isJSON()
// -> true
parseQuery( )

toQueryParamsのアリアスである。

toQueryParams([separator = '&'])

URLのパラメータを解析し、オブジェクトとして返す。
注:値がないパラメータはundefinedとして解析する。

'section=blog&id=45'.toQueryParams();
// -> {section: 'blog', id: '45'}

'section=blog;id=45'.toQueryParams();
// -> {section: 'blog', id: '45'}

'http://www.example.com?section=blog&id=45#comments'.toQueryParams();
// -> {section: 'blog', id: '45'}

'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams();
// -> {section: 'blog', tag: ['javascript', 'prototype', 'doc']}

'tag=ruby%20on%20rails'.toQueryParams();
// -> {tag: 'ruby on rails'}

'id=45&raw'.toQueryParams();
// -> {id: '45', raw: undefined}
scan(pattern, iterator)

指定したパターンで文字列をiterateする。

>>> var fruits = []; 
>>> 'apple, pear & orange'.scan(/\w+/, function(match){ fruits.push(match[0])});
"apple, pear & orange"
>>> fruits
["apple", "pear", "orange"]
>>> fruits.inspect();
"['apple', 'pear', 'orange']"

注:正規表現で「g」を使用しないで下さい。無限ループになる可能性があります。

strip( )

文字列の頭と末尾のスペースを無くす。

'    hello world!    '.strip();
// -> 'hello world!'
stripScripts( )

文字列からHTMLのScriptタグと内容を弾ける。

'a <a href="#">link</a><script>alert("hello world!")</script>'.stripScripts();
// -> 'a <a href="#">link</a>'
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!")'

'a <a href="#">link</a><script>alert("hello world!")</script>'.stripScripts().stripTags();
// -> 'a link'
sub(pattern, replacement[, count = 1])

gsubと違って、グローバル置換ではなく、デフォルト最初出現した部分を置換する。
正規表現の解析などについてgsunと同じである。

var fruits = 'apple pear orange';

 fruits.sub(' ', ', ');
// -> 'apple, pear orange'

 fruits.sub(' ', ', ', 1);
// -> 'apple, pear orange'

 fruits.sub(' ', ', ', 2);
// -> 'apple, pear, orange'

注:正規表現で「g」を使用しないで下さい。無限ループになる可能性があります。

succ()

文字列の最後の文字をUNICODEの次の文字に変換する。

'a'.succ();
// -> 'b'
'あ'.succ();
//-> "ぃ"
'1'.succ();
//-> "2"
'あいう'.succ();
//-> "あいぇ"
times(count)

文字列をCount回繋いで返す。

"echo ".times(3);
//-> "echo echo echo "
toArray( )

文字列の文字を分割し、配列で返す。

'hello world!'.toArray();
// -> ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
toJSON( )

JSON文字列で返す。

'The "Quoted" chronicles'.toJSON();
//-> '"The \"Quoted\" chronicles"'
truncate([length = 30[, suffix = '...']])

文字列を指定した長さで切断し、Suffix文字列を繋ぐ。(抜粋)

'A random sentence whose length exceeds 30 characters.'.truncate();
// -> 'A random sentence whose len...'

'Some random text'.truncate(10, ' [...]');
// -> 'Some [...]'
underscore( )

Camelスタイル文字列を分割し、アンダーラインで繋ぐ。

'borderBottomWidth'.underscore();
// -> 'border_bottom_width'
unescapeHTML()

文字列でのHTMLタグとタグのコードを無くす。

'<h1>Pride &amp; Prejudice</h1>'.unescapeHTML()
// -> 'Pride & Prejudice'
unfilterJSON([filter = Prototype.JSONFilter])

コメントをはずす。

'/*-secure-\n{"name": "Violet", "occupation": "character", "age": 25}\n*/'.unfilterJSON()
// -> '{"name": "Violet", "occupation": "character", "age": 25}'