Movatterモバイル変換


[0]ホーム

URL:


  1. 給開發者的 Web 技術文件
  2. JavaScript
  3. JavaScript 參考文件
  4. 標準內建物件
  5. 字串

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in EnglishAlways switch to English

字串

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

* Some parts of this feature may have varying levels of support.

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饋頁
\uXXXXunicode 代碼
\u{X} ...\u{XXXXXX}unicode 代碼實驗性質
\xXXLatin-1 字元

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

長字面值字串

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

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

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

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

js
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 方法:

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

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

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

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

比較字串

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

js
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 物件和原始字串(BooleanNumbers 也是如此)。

String literals (denoted by double or single quotes) and strings returned fromString calls in a non-constructor context (i.e., without using thenew keyword) are primitive strings. JavaScript automatically converts primitives toString objects, so that it's possible to useString 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.

js
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 物件則會回傳,且被視作是其他物件。舉個例子:

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

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

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

js
console.log(eval(s2.valueOf())); // 回傳數字 4

屬性

String.prototype

能讓字串物件增加屬性。

方法

String.fromCharCode()

利用 Unicode 值的序列建立並回傳一個字串。

String.fromCodePoint()實驗性質

利用編碼位置的序列建立並回傳一個字串。

String 通用方法

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

TheString 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:

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

Generics are also available onArray methods.

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

js
/*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.length

Reflects thelength of the string. Read-only.

Methods

String.prototype.at()

Returns the character (exactly one UTF-16 code unit) at the specifiedindex. Accepts negative integers, which count back from the last string character.

String.prototype.charAt()

Returns the character (exactly one UTF-16 code unit) at the specifiedindex.

String.prototype.charCodeAt()

Returns a number that is the UTF-16 code unit value at the givenindex.

String.prototype.codePointAt()

Returns a nonnegative integer Number that is the code point value of the UTF-16encoded code point starting at the specifiedpos.

String.prototype.concat()

Combines the text of two (or more) strings and returns a new string.

String.prototype.includes()

Determines whether the calling string containssearchString.

String.prototype.endsWith()

Determines whether a string ends with the characters of the stringsearchString.

String.prototype.indexOf()

Returns the index within the callingString object of the firstoccurrence ofsearchValue, or-1 if not found.

String.prototype.lastIndexOf()

Returns the index within the callingString object of the lastoccurrence ofsearchValue, or-1 if not found.

String.prototype.localeCompare()

Returns a number indicating whether the reference stringcompareString comes before, after, or is equivalent to thegiven string in sort order.

String.prototype.match()

Used to match regular expressionregexp against a string.

String.prototype.matchAll()

Returns an iterator of allregexp's matches.

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 and returns a new string ofthe lengthtargetLength.

String.prototype.padStart()

Pads the current string from the start with a given string and returns a new stringof the lengthtargetLength.

String.prototype.repeat()

Returns a string consisting of the elements of the object repeatedcount times.

String.prototype.replace()

Used to replace occurrences ofsearchFor usingreplaceWith.searchFor may be a stringor Regular Expression, andreplaceWith may be a string orfunction.

String.prototype.replaceAll()

Used to replace all occurrences ofsearchFor usingreplaceWith.searchFor may be a stringor Regular Expression, andreplaceWith may be a string orfunction.

String.prototype.search()

Search for a match between a regular expressionregexp andthe calling string.

String.prototype.slice()

Extracts a section of a string and returns a new string.

String.prototype.split()

Returns an array of strings populated by splitting the calling string at occurrencesof the substringsep.

String.prototype.startsWith()

Determines whether the calling string begins with the characters of stringsearchString.

String.prototype.substring()

Returns a new string containing characters of the calling string from (or between)the specified index (or indices).

String.prototype.toLocaleLowerCase()

The characters within a string are converted to lowercase while respecting thecurrent locale.

For most languages, this will return the same astoLowerCase().

String.prototype.toLocaleUpperCase( [locale, ...locales])

The characters within a string are converted to uppercase while respecting thecurrent locale.

For most languages, this will return the same astoUpperCase().

String.prototype.toLowerCase()

Returns the calling string value converted to lowercase.

String.prototype.toString()

Returns a string representing the specified object. Overrides theObject.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.

String.prototype.trimStart()

Trims whitespace from the beginning of the string.

String.prototype.trimEnd()

Trims whitespace from the end of the string.

String.prototype.valueOf()

Returns the primitive value of the specified object. Overrides theObject.prototype.valueOf() method.

String.prototype[Symbol.iterator]()

Returns a new iterator object that iterates over the code points of a String value,returning each code point as a String value.

Examples

String conversion

It's possible to useString as a "safer"toString alternative, as although it still normally calls the underlyingtoString, it also works fornull andundefined. For example:

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

規範

Specification
ECMAScript® 2026 Language Specification
# sec-string-objects

瀏覽器相容性

參見

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp