MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-survey

There was a scripting error on this page. While it is being addressed by site editors, you can view partial content below.

This translation is in progress.

{{JSRef}}

Stringวัตถุทั่วโลกเป็นตัวสร้างสำหรับสตริงหรือลำดับของตัวอักษรที่

วากยสัมพันธ์

อักษร literals ใช้รูปแบบ:

'ข้อความสตริง'
"สตริงข้อความ"
"中文español deutsch ภาษาไทยहिन्दीالعربيةภาษาโปรตุเกสภาษาโปรตุเกสภาษาโปรตุเกสภาษาโปรตุเกสภาษาโปรตุเกสภาษาโปรตุเกสภาษาโปรตุเกสการแปล

สตริงยังสามารถสร้างโดยใช้Stringอ็อบเจ็กต์ global ได้โดยตรง:

สตริง (สิ่งที่)

พารามิเตอร์

thing
สิ่งที่ต้องแปลงเป็นสตริง

ตัวอักษรแม่แบบ

เริ่มต้นด้วย ECMAScript 2015 ตัวอักษรแบบสตริงยังสามารถเรียกได้ว่าตัวอักษรแม่แบบ :

`สวัสดีชาวโลก '
`Hello!
 โลก! `
`hello ${who}`
escape `<a>${who}</a>`

Escape notation

Besides regular, printable characters, special characters can be encoded using escape notation:

Code Output
\0 the NULL character
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\v vertical tab
\t tab
\b backspace
\f form feed
\uXXXX unicode codepoint
\u{X} ... \u{XXXXXX} unicode codepoint {{experimental_inline}}
\xXX the Latin-1 character

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

Long literal strings

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

You can use the + operator to append multiple strings together, like this:

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

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

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

Both of these result in identical strings being created.

Description

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

Character access

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

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

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

Comparing strings

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

var a = 'a';
var b = 'b';
if (a < b) { // true
  console.log(a + ' is less than ' + b);
} else if (a > b) {
  console.log(a + ' is greater than ' + b);
} else {
  console.log(a + ' and ' + b + ' are equal.');
}

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

Distinction between string primitives and String objects

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "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 {{jsxref("Operators/new", "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); // Logs "string"
console.log(typeof s_obj);  // Logs "object"

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

var s1 = '2 + 2';             // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1));        // returns the number 4
console.log(eval(s2));        // returns the string "2 + 2"

For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

console.log(eval(s2.valueOf())); // returns the number 4
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.

Properties

{{jsxref("String.prototype")}}
Allows the addition of properties to a String object.

Methods

{{jsxref("String.fromCharCode()")}}
Returns a string created by using the specified sequence of Unicode values.
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
Returns a string created by using the specified sequence of code points.
{{jsxref("String.raw()")}} {{experimental_inline}}
Returns a string created from a raw template string.

String generic methods

String generics are non-standard, deprecated and will get removed near future.

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

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

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

String instances

Properties

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}

Methods

Methods unrelated to HTML

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}

HTML wrapper methods

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}

Examples

String conversion

It's possible to use String as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:

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

ข้อมูลจำเพาะ

สเปค สถานะ คิดเห็น
{{SpecName ( 'ES1')}} {{Spec2 ( 'ES1')}} ความหมายเบื้องต้น
{{SpecName ('ES5.1', ​​'# sec-15.5', 'String')}} {{Spec2 ( 'ES5.1')}}  
{{SpecName ('ES2015', '# sec-string-objects', 'String')}} {{Spec2 ( 'ES2015')}}  
{{SpecName ('ESDraft', '# sec-string-objects', 'String')}} {{Spec2 ( 'ESDraft')}}  

ความเข้ากันได้ของเบราเซอร์

{{compat ( "javascript.builtins.String.String")}}

ดูสิ่งนี้ด้วย

Document Tags and Contributors

 ผู้มีส่วนร่วมกับหน้านี้: may583
 อัปเดตล่าสุดโดย: may583,