String 全域物件為字串的構造函數,或是一個字符序列。

語法

字串文字採用下列形式:

'string text' "string text" "中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"

字串也可以被全域的 String 物件建立:

String(thing)

參數

thing
任何要轉換成字串的物件。

模板文字

自 ECMAScript 2015,字串文字也可以是 Template literals

`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`

跳脫符號

除了常規的、可印出來的字元,特殊字元也可以被跳脫符號來表示編碼。

代碼 輸出
\0 空字元
\' 單引號
\" 雙引號
\\ 反斜線
\n 斷行
\r 回車
\v 垂直制表
\t 制表
\b 退格
\f 饋頁
\uXXXX unicode 代碼
\u{X} ... \u{XXXXXX} unicode 代碼
\xXX Latin-1 字元

和其他語言不同,JavaScript 將單引號字串和雙引號字串是做相同;因此,上述的序列可以在單引號或雙引號中作用。

長文字串

有些時候,你的程式碼會包含非常長的字串。 為了不讓長字串無止盡地往下長,抑或是在你心血來潮的時候,你可能希望將這樣長的字串能夠斷成多行卻不影響到實際的內容。

你可以用 + 預算子附加多個字串在一起,像是這樣:

let longString = "This is a very long string which needs " +
                 "to wrap across multiple lines because " +
                 "otherwise my code is unreadable.";

或者,你可以在每一行尾端用反斜線字元("\")表示字串會繼續被顯示在下一列。 你必須要確定在反斜線後面沒有任何空白或其他字元,甚至是縮排;否則這個方法將失效。 這個形式看起來像這樣:

let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";

這兩個方法都會建立相同的字串內容。

說明

字串對於能保留以文字形式表達的資料這件事來說,是有用的。在字串上,一些最常被使用的運算即確認字串長度 length ,用 + 或 += 字串運算元 建造或者串接字串,用 indexOf 方法檢查子字串是否存在或子字串的位置,或者是用 substring 方法將子字串抽取出來。

存取字元

有兩個方法可以存取字串中個別的字元。第一個是用 charAt 方法:

return 'cat'.charAt(1); // 回傳 "a"

另一個(在ECMAScript 5中被提到)方法是將字串當作一個類似陣列的物件,直接存取字串中對應的數值索引。

return 'cat'[1]; // 回傳 "a"

對於存取字元使用的括號表達式,沒辦法去刪除或指派一個值給這些屬性。 這些屬性既非可寫的,也非可設定的。(參見 Object.defineProperty)

比較字串

C 語言的開發者有 strcmp() 函式可以用來比較字串。 在 JavaScript 中,你只能用小於和大於運算子

var a = "a";
var b = "b";
if (a < b) // true
  print(a + " 小於 " + b);
else if (a > b)
  print(a + " 大於 " + b);
else
  print(a + " 和 " + b + " 相等");

這樣類似的結果,也能使用繼承 String 實體的 localeCompare 方法來實現。

分辨 string 原始型別和 String 

請注意,JavaScript 會區別 String 物件和原始字串(Boolean 和 Numbers 也是如此)。

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

var s_prim = "foo";
var s_obj = new String(s_prim);

console.log(typeof s_prim); // 印出 "string"
console.log(typeof s_obj);  // 印出 "object"

字串原始型別和 String 物件也會在使用 eval 時給出不同的結果。 原始型別傳進 eval 會被視為原始代碼;String 物件則會回傳,且被視作是其他物件。舉個例子:

s1 = "2 + 2";               // 建立一個字串原始型別
s2 = new String("2 + 2");   // 建立一個字串物件
console.log(eval(s1));      // 回傳數字 4
console.log(eval(s2));      // 回傳字串 "2 + 2"

因為一些原因,程式碼也許在遇到 String 物件時,但需要的卻是字串原始型別;儘管如此,通常作者們不需要擔心它的差異。

一個 String 物件總能夠使用 valueOf 方法被轉換成自身的原始副本。

console.log(eval(s2.valueOf())); // 回傳數字 4
注意: 對於在 JavaScript 中其他可用的字串方法,請參閱這篇文章StringView – a C-like representation of strings based on typed arrays

屬性

For properties available on 字串 instances, see Properties of 字串 instances.

String.prototype
能讓字串物件增加屬性。
Properties inherited from Function:

方法

For methods available on 字串 instances, see Methods of 字串 instances.

String.fromCharCode()
利用 Unicode 值的序列建立並回傳一個字串。
String.fromCodePoint()
利用編碼位置的序列建立並回傳一個字串。
Methods inherited from Function:

String 通用方法

字串通用方法是非標準化的、被棄用的,也有近期將被刪除的。

The String instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:

var num = 15;
alert(String.replace(num, /5/, '2'));

Generics are also available on Array methods.

The following is a shim to provide support to non-supporting browsers:

/*globals define*/
// Assumes all supplied String instance methods already present
// (one may use shims for these if not available)
(function () {
    'use strict';

    var i,
        // We could also build the array of methods with the following, but the
        //   getOwnPropertyNames() method is non-shimable:
        // Object.getOwnPropertyNames(String).filter(function (methodName)
        //  {return typeof String[methodName] === 'function'});
        methods = [
            'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
            'replace', 'split', 'substr', 'concat', 'slice'
        ],
        methodCount = methods.length,
        assignStringGeneric = function (methodName) {
            var method = String.prototype[methodName];
            String[methodName] = function (arg1) {
                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i < methodCount; i++) {
        assignStringGeneric(methods[i]);
    }
}());

String instances

Properties

String.prototype.constructor
Specifies the function that creates an object's prototype.
String.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.

Methods unrelated to HTML

String.prototype.charAt()
Returns the character at the specified index.
String.prototype.charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.
String.prototype.codePointAt()
Returns a non-negative integer that is the UTF-16 encoded code point value at the given position.
String.prototype.concat()
Combines the text of two strings and returns a new string.
String.prototype.includes()
Determines whether one string may be found within another string.
String.prototype.endsWith()
Determines whether a string ends with the characters of another string.
String.prototype.indexOf()
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
String.prototype.lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
String.prototype.localeCompare()
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
String.prototype.match()
Used to match a regular expression against a string.
String.prototype.normalize()
Returns the Unicode Normalization Form of the calling string value.
String.prototype.padEnd()
Pads the current string from the end with a given string to create a new string from a given length.
String.prototype.padStart()
Pads the current string from the start with a given string to create a new string from a given length.
String.prototype.quote()
Wraps the string in double quotes (""").
String.prototype.repeat()
Returns a string consisting of the elements of the object repeated the given times.
String.prototype.replace()
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
String.prototype.search()
Executes the search for a match between a regular expression and a specified string.
String.prototype.slice()
Extracts a section of a string and returns a new string.
String.prototype.split()
Splits a String object into an array of strings by separating the string into substrings.
String.prototype.startsWith()
Determines whether a string begins with the characters of another string.
String.prototype.substr()
Returns the characters in a string beginning at the specified location through the specified number of characters.
String.prototype.substring()
Returns the characters in a string between two indexes into the string.
String.prototype.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().
String.prototype.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().
String.prototype.toLowerCase()
Returns the calling string value converted to lower case.
String.prototype.toSource()
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource() method.
String.prototype.toString()
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
String.prototype.toUpperCase()
Returns the calling string value converted to uppercase.
String.prototype.trim()
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
String.prototype.trimLeft()
Trims whitespace from the left side of the string.
String.prototype.trimRight()
Trims whitespace from the right side of the string.
String.prototype.valueOf()
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.
String.prototype[@@iterator]()
Returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value.

HTML wrapper methods

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

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

Examples

String conversion

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]));
}

Specifications

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'String' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String' in that specification.
Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 0.2 (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

文件標籤與貢獻者

 此頁面的貢獻者: jsgao0, jackblackevo, iigmir, teoli, fscholz
 最近更新: jsgao0,