String

このページの最終更新日は、2010 年 09 月 19 日です。版が古くなっています。英語版の最新の内容もあわせて参照して下さい。

概要

文字列 (String) は一続きの文字です。

構文

new String()
new String(string)

String リテラルは以下の形式を取ります。

stringText'
"stringText"

引数

string
任意の文字列
stringText
恐らくエンコードされている一続きの文字。

説明

String オブジェクトは、new String() コンストラクタが呼び出されることによって、生成されます。String オブジェクトは、以下で記述されるメソッドを使って、プリミティブデータ型である、 Javascript の文字列をラップします。new を前につけずに呼び出されるグローバル関数 String() でも、プリミティブである文字列を生成することができます。JavaScript における文字列リテラルは、プリミティブな文字列です。

Javascript は String プリミティブと String オブジェクトを自動的に変換するので、String プリミティブである文字列上で String オブジェクトのあらゆるメソッドを呼ぶことができます。JavaScript は String プリミティブを一時的な String オブジェクトに自動的に変換してから、そのメソッドを呼び、そのあと、その一時的な String オブジェクトを捨てます。例えば、文字列リテラルから生成された String プリミティブ上で、String.length プロパティを使うことができます。:

s_obj.length;       // 3
s_prim.length;      // 3
s_also_prim.length; // 3
'foo'.length;       // 3
"foo".length;       // 3

(文字列リテラルを表すには、シングルもしくはダブルクオーテーションマークを使うことができます。)

String オブジェクトは String.valueOf() でプリミティブである文字列に変換することが可能です。

String プリミティブと String オブジェクトは、Javascript として評価されたとき、異なる結果を与えます。プリミティブはソースコードとして扱われ、一方、String オブジェクトは、文字がそのまま連続した状態のオブジェクトとして扱われます。例:

s1 = "2 + 2"; // String プリミティブを生成します
s2 = new String("2 + 2"); // String オブジェクトを生成します
eval(s1);     // 数字の 4 を返します
eval(s2);     // 文字列の "2 + 2" を返します
eval(s2.valueOf()); // 数字の 4 を返します

文字へのアクセス

文字列内の個々の文字にアクセスするには、二つの方法があります。一つ目の方法は、charAt メソッドです。:

'cat'.charAt(1); // "a" を返します。

もう一つの方法は、文字列を配列として扱うことです。各々の添え字が個々の文字に対応します。:

return 'cat'[1]; // "a" を返します。
二つ目の方法(文字列を配列として扱う方法)は、ECMAScript の一部ではありません。これは、JavaScript の機能です。

両方の場合において、単一の文字を設定しようとしても、動作しないでしょう。charAt を通して文字を設定しようとすると、エラーになります。:

var x = 'cat';
x.charAt(0) = 'b'; // エラー

添え字から文字を設定するとエラーになりませんが、文字列自身は変化しません。:

var x = 'cat';
x[2] = 'p';
print(x);    // 依然として、 'cat' を出力します
print(x[2]); // 依然として、 't' を出力します

文字列同士の比較

C 開発者は、文字列同士の比較のために strcmp() 関数を使います。JavaScript では、単純に、小なり及び大なり演算子を使ってください。

var a = "a";
var b = "b";

if (a < b) // 真
    print(a + " は " + b + " より小さい。");
else if (a > b)
    print(a + " は " + b + " より大きい。");
else
    print(a + " と " + b + " は等しい。");

同じような結果を、String インスタンスから継承される localeCompare を使用して得ることができます。

プロパティ

String インスタンスから継承されているPropertiesについては、String インスタンスのPropertiesを参照してください。
prototype
オブジェクトのプロトタイプを生成する関数を指定します。
Function から継承されるプロパティ

メソッド

String インスタンスから継承されているMethodsについては、String インスタンスのMethodsを参照してください。
fromCharCode
Unicode の値の指定されたシーケンスによって生成された文字列を返します。
Function から継承されるメソッド

String インスタンス

プロパティ

constructor
Specifies the function that creates an object's prototype.
length
Reflects the length of the string.
N
Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of length. These properties are read-only.
Properties inherited from Object:
constructor

メソッド

Methods

Methods unrelated to HTML

charAt
Returns the character at the specified index.
charCodeAt
Returns a number indicating the Unicode value of the character at the given index.
concat
Combines the text of two strings and returns a new string.
indexOf
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
match
Used to match a regular expression against a string.
quote
Non-standard
Wraps the string in double quotes (""").
replace
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search
Executes the search for a match between a regular expression and a specified string.
slice
Extracts a section of a string and returns a new string.
split
Splits a String object into an array of strings by separating the string into substrings.
substr
Returns the characters in a string beginning at the specified location through the specified number of characters.
substring
Returns the characters in a string between two indexes into the string.
toLocaleLowerCase
The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as toLowerCase.
toLocaleUpperCase
The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as toUpperCase.
toLowerCase
Returns the calling string value converted to lower case.
toSource
Non-standard
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource method.
toString
Returns a string representing the specified object. Overrides the Object.prototype.toString method.
toUpperCase
Returns the calling string value converted to uppercase.
trim
Requires JavaScript 1.8.1
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
trimLeft
Requires JavaScript 1.8.1 Non-standard
Trims whitespace from the left side of the string.
trimRight
Requires JavaScript 1.8.1 Non-standard
Trims whitespace from the right side of the string.
valueOf
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf method.

HTML wrapper methods

Non-standard

Should we change these to point to our own docs rather than W3C? In any case, they're staying as is for now because with the current structure of the HTML pages here at MDC, we cannot reference specific attributes as necessary anyway (e.g., the difference between the anchor method and the link method). Each of the following methods returns a copy of the string wrapped inside the appropriate HTML tag.

anchor
<a name="name"> (hypertext target)
big
<big>
blink
<blink>
bold
<b>
fixed
<tt>
fontcolor
<font color="color">
fontsize
<font size="size">
italics
<i>
link
<a href="url"> (link to URL)
small
<small>.
strike
<strike>
sub
<sub>
sup
<sup>

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

Methods inherited from Object:
toSource

例

It's possible to use String as a "safer" toString alternative, as although it still normally calls the underlying toString, it also works for null and undefined. For example:

var outputStrings = [];
for (let i = 0, n = inputValues.length; i < n; ++i) {
  outputStrings.push(String(inputValues[i]));
}

ブラウザ実装状況

機能 Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
基本サポート 0.2 (Yes) 9.0 (Yes) (Yes)
機能 Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
基本サポート (Yes) (Yes) (Yes) (Yes) (Yes)

タグ (3)

Contributors to this page: saneyuki_s, Potappo, ethertank, Mgjbot
Last updated by: ethertank,
Last reviewed by: ethertank,