From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../reference/global_objects/string/index.html | 405 --------------------- .../global_objects/string/match/index.html | 160 -------- .../global_objects/string/normalize/index.html | 146 -------- .../global_objects/string/repeat/index.html | 118 ------ .../global_objects/string/replace/index.html | 233 ------------ .../global_objects/string/slice/index.html | 138 ------- .../global_objects/string/startswith/index.html | 128 ------- .../global_objects/string/substr/index.html | 121 ------ .../global_objects/string/substring/index.html | 195 ---------- 9 files changed, 1644 deletions(-) delete mode 100644 files/vi/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/match/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/normalize/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/repeat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/replace/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/slice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/startswith/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substr/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substring/index.html (limited to 'files/vi/web/javascript/reference/global_objects/string') diff --git a/files/vi/web/javascript/reference/global_objects/string/index.html b/files/vi/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index c9f5680a0c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Reference - - String - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
-

lnyannini

- -

HTML

- -
Nội dung HTML mẫu
- -

CSS

- -
Nội dung CSS mẫu
- -

JavaScript

- -
Nội dung JavaScript mẫu
- -

Kết quả

- -

{{EmbedLiveSample('lnyannini')}}

-f}} - -

Copy dtoc: june-12-2017
- The String global object is a constructor for strings, or a sequence of characters.
- Đối tượng Chuỗi toàn cục là một constructor cho chuỗi, hoặc chuỗi ký tự.

- -

Syntax

- -

String literals take the forms:

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

Strings can also be created using the String global object directly:

- -
String(thing)
- -

Parameters

- -
-
thing
-
Anything to be converted to a string.
-
- -

Template literals

- -

Starting with ECMAScript 2015, string literals can also be so-called Template literals:
- Trong ES6 Chuỗi cũng được gọi là Template Strings.

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

Escape notation

- -

Beside regular, printable characters, special characters can be encoded using escape notation:
- Ngoài ký tự thường, các ký tự đặc biệt có thể được code ra bằng cách dùng các ký hiệu loại trừ:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe 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, 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 "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

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

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{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')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/match/index.html b/files/vi/web/javascript/reference/global_objects/string/match/index.html deleted file mode 100644 index d40ffc4482..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/match/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: String.prototype.match() -slug: Web/JavaScript/Reference/Global_Objects/String/match -tags: - - Biểu thức chính quy - - Chuỗi - - Phương Thức -translation_of: Web/JavaScript/Reference/Global_Objects/String/match ---- -
{{JSRef}}
- -
 
- -

Phương thức match() đưa ra những so khớp khi so khớp một chuỗi (string) với biểu thức chính quy.

- -

Cú pháp

- -
str.match(regexp)
- -

Tham số

- -
-
regexp
-
Đối tượng biểu thức chính quy.  Nếu một đối tượng obj không phải biểu thức chính quy được truyền vào, nó sẽ ngầm chuyển đổi thành một {{jsxref("RegExp")}} bằng cách sử dụng new RegExp(obj). Nếu bạn không truyền tham số và sử dụng trực tiếp phương thức match(), bạn sẽ nhận lại một {{jsxref("Array")}} với một chuỗi rỗng: [""].
-
- -

Giá trị trả về

- -

Nếu một chuỗi khớp với biểu thức, nó sẽ trả lại một {{jsxref("Array")}} chứa chuỗi khớp hoàn toàn là phần tử đầu tiên, tiếp đó là các kết quả nằm trong dấu ngoặc đơn (ngoặc có nhớ). Nếu không có so khớp, nó sẽ trả về {{jsxref("null")}}.

- -

Mô tả

- -

Nếu một biểu thức chính quy không có cờ gstr.match() trả về kết quả giống như  {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. {{jsxref("Array")}} trả về có thêm thuộc tính input chứa chuỗi ban đầu được phân tích ngữ pháp. Thêm nữa, nó có một thuộc tính index đại diện cho chỉ mục (tính từ 0) của so khớp trong chuỗi.

- -

Nếu biểu thức chính quy có cờ g, phương thức trả về một {{jsxref("Array")}} chứa tất cả chuỗi con khớp mà không phải các đối tượng khớp. Nó không trả về chuỗi trong dấu ngoặc tròn có nhớ. Nếu không có so khớp, phương thức trả về {{jsxref("null")}}.

- -

Xem thêm: Các phương thức RegEx

- - - -

Ví dụ

- -

Sử dụng match()

- -

Trong ví dụ dưới đây, match() được dùng để tìm chuỗi 'Chapter ' theo sau là một hoặc nhiều kí tự số, tiếp đó là một dấu chấm . thập phân và một số lặp lại 0 hoặc nhiều lần. Biểu thức chính quy có cờ i nên không phân biệt chữ hoa và thường.

- -
var str = 'For more information, see Chapter 3.4.5.1';
-var re = /see (chapter \d+(\.\d)*)/i;
-var found = str.match(re);
-
-console.log(found);
-
-// logs [ 'see Chapter 3.4.5.1',
-//        'Chapter 3.4.5.1',
-//        '.1',
-//        index: 22,
-//        input: 'For more information, see Chapter 3.4.5.1' ]
-
-// 'see Chapter 3.4.5.1' là so khớp toàn bộ.
-// 'Chapter 3.4.5.1' được bắt bởi '(chapter \d+(\.\d)*)'.
-// '.1' là giá trị cuối cùng được bắt bởi '(\.\d)'.
-// Thuộc tính 'index' (22) là chỉ mục tính từ 0 của so khớp toàn bộ.
-// Thuộc tính 'input' là chuỗi gốc đã được phân tích ngữ pháp.
- -

Sử dụng cờ toàn cục và cờ không phân biệt chữ hoa/thường với match()

- -

Ví dụ dưới đây mô tả cách sử dụng cờ g và cờ i với match(). Tất cả chữ A tớ E và a tới e sẽ được trả lại và mỗi phần từ khớp nằm trong mảng.

- -
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
-var regexp = /[A-E]/gi;
-var matches_array = str.match(regexp);
-
-console.log(matches_array);
-// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
-
- -

Sử dụng match() không truyền tham số

- -
var str = "Nothing will come of nothing.";
-
-str.match();   //trả về [""]
- -

Một đối tượng không phải biểu thức chính quy được coi như một tham số

- -

Khi tham số là một chuỗi hoặc một số, ngầm định, nó được chuyển đổi thành một {{jsxref("RegExp")}} sử dụng new RegExp(obj). Nếu nó là một số dương với một dấu dương, phương thức Regexp() sẽ bỏ qua dấu dương.

- -
var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
-    str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
-    str3 = "The contract was declared null and void.";
-str1.match("number");   // "number" là một chuỗi. Trả về ["number"]
-str1.match(NaN);        // kiểu của NaN là kiểu number. Trả về ["NaN"]
-str1.match(Infinity);   // kiểu của Infinity là number. Trả về ["Infinity"]
-str1.match(+Infinity);  // Trả về ["Infinity"]
-str1.match(-Infinity);  // Trả về ["-Infinity"]
-str2.match(65);         // Trả về ["65"]
-str2.match(+65);        // Một số với dấu dương. Trả về ["65"]
-str3.match(null);       // Trả về ["null"]
- -

Thông số

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiBình luận
{{SpecName('ES3')}}{{Spec2('ES3')}} -

Định nghĩa ban đầu. Được bổ sung trong JavaScript 1.2.

-
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.builtins.String.match")}}

- -

Lưu ý cho Firefox

- - - -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html b/files/vi/web/javascript/reference/global_objects/string/normalize/index.html deleted file mode 100644 index faf26687eb..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: String.prototype.normalize() -slug: Web/JavaScript/Reference/Global_Objects/String/normalize -tags: - - Chuỗi - - ECMAScript 2015 - - JavaScript - - Phương Thức - - Prototype - - String - - Tham khảo - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize ---- -
{{JSRef}}
- -

Phương thức normalize() trả về chuỗi với các ký tự Unicode đã được bình thường hóa (nếu giá trị truyền vào không phải chuỗi, nó sẽ được chuyển thành chuỗi trước).

- -
{{EmbedInteractiveExample("pages/js/string-normalize.html")}}
- - - -

Cú pháp

- -
str.normalize([form])
- -

Tham số

- -
-
form
-
Là một trong các giá trị "NFC", "NFD", "NFKC", hoặc "NFKD", để chỉ định định dạng Unicode của chuỗi ký tự. Nếu bỏ qua hoặc mang giá trị {{jsxref("undefined")}}, "NFC" sẽ được sử dụng. -
    -
  • NFC — Normalization Form Canonical Composition. (Unicode Dựng Sẵn)
  • -
  • NFD — Normalization Form Canonical Decomposition. (Unicode Tổ Hợp)
  • -
  • NFKC — Normalization Form Compatibility Composition. (Unicode Dựng Sẵn Tương Thích)
  • -
  • NFKD — Normalization Form Compatibility Decomposition. (Unicode Tổ Hợp Tương Thích)
  • -
-
-
- -

Giá trị trả về

- -

Một chuỗi mới với các ký tự Unicode đã được bình thường hóa.

- -

Lỗi có thể gây ra

- -
-
{{jsxref("RangeError")}}
-
Phương thức sẽ gây ra lỗi {{jsxref("RangeError")}} nếu như giá trị tham số form không phải là một trong các giá trị liệt kê ở trên.
-
- -

Mô tả

- -

Phương thức normalize() sẽ trả về một chuỗi mới với các ký tự Unicode đã được bình thường hóa theo một trong các định dạng Unicode Normalization Form. Nó không làm thay đổi chuỗi ban đầu.

- -
-

Đối với tiếng Việt, việc bình thường hóa giữa hai định dạng Canonical hoặc Compatibility (cùng Tổ Hợp hoặc Dựng Sẵn) là như nhau.

-
- -

Ví dụ

- -

Sử dụng normalize()

- -
// Chuỗi ban đầu
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-var str = '\u1E9B\u0323';
-
-
-// Canonically-composed form (NFC)
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-str.normalize('NFC'); // '\u1E9B\u0323'
-str.normalize();      // như trên
-
-
-// Canonically-decomposed form (NFD)
-
-// U+017F: LATIN SMALL LETTER LONG S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFD'); // '\u017F\u0323\u0307'
-
-
-// Compatibly-composed (NFKC)
-
-// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
-str.normalize('NFKC'); // '\u1E69'
-
-
-// Compatibly-decomposed (NFKD)
-
-// U+0073: LATIN SMALL LETTER S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFKD'); // '\u0073\u0323\u0307'
-
-// So sánh chuỗi tiếng Việt:
-
-// Unicode Dựng Sẵn
-var tvds = 'Tiếng Việt';
-// Unicode Tổ Hợp
-var tvth = 'Tiếng Việt';
-
-console.log(tvds.length); // 10
-console.log(tvth.length); // 14
-console.log(tvds == tvth); // false
-console.log(tvds.normalize('NFC') == tvth.normalize('NFC')); // true
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.String.normalize")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html b/files/vi/web/javascript/reference/global_objects/string/repeat/index.html deleted file mode 100644 index 72e2179cf1..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.repeat() -slug: Web/JavaScript/Reference/Global_Objects/String/repeat -tags: - - Chuỗi - - ES6 - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat ---- -
{{JSRef}}
- -

Phương thức repeat() xây dựng và trả về một chuỗi mới chứa số lượng nhất định bản sao chép của chuỗi được gọi tới và nối chung với nhau.

- -

Cú pháp

- -
str.repeat(count);
-
- -

Tham số

- -
-
count
-
Là 0 hoặc số nguyên dương, tức là giá trị nằm trong khoảng: [0, +∞), xác định số lần lặp để tạo chuỗi mới.
-
- -

Giá trị trả về

- -

Một chuỗi mới chứa số lần sao chép (count) chuỗi đầu vào.

- -

Ngoại lệ

- - - -

Ví dụ

- -
'abc'.repeat(-1);   // RangeError
-'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (tham số đếm sẽ được chuyển thành số nguyên)
-'abc'.repeat(1/0);  // RangeError
-
-({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
-// 'abcabc' (repeat() is a generic method)
-
- -

Polyfill

- -

Phương thức này đã được thêm vào kỹ thuật ES6 và có thể chưa có sẵn trong tất cả các bản bổ sung JS. Tuy nhiên bạn có thể sử dụng polyfill String.prototype.repeat() với snippet dưới đây:

- -
if (!String.prototype.repeat) {
-  String.prototype.repeat = function(count) {
-    'use strict';
-    if (this == null) {
-      throw new TypeError('can\'t convert ' + this + ' to object');
-    }
-    var str = '' + this;
-    count = +count;
-    if (count != count) {
-      count = 0;
-    }
-    if (count < 0) {
-      throw new RangeError('repeat count must be non-negative');
-    }
-    if (count == Infinity) {
-      throw new RangeError('repeat count must be less than infinity');
-    }
-    count = Math.floor(count);
-    if (str.length == 0 || count == 0) {
-      return '';
-    }
-
-    // Đảm bảo tham số đếm là số nguyên 31 bít cho phép ta tối ưu hóa nhiều
-    // phần chính. Nhưng dù sao thì, hầu hết các trình duyệt hiện tại (tháng Tám năm 2014) không thể xử lý
-    // các chuỗi 1 << 28 chars hoặc lớn hơn, vậy nên:
-    if (str.length * count >= 1 << 28) {
-      throw new RangeError('repeat count must not overflow maximum string size');
-    }
-    var rpt = '';
-    for (var i = 0; i < count; i++) {
-      rpt += str;
-    }
-    return rpt;
-  }
-}
-
- -

Thông số

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES2015')}}Định nghĩa bổ sung.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.builtins.String.repeat")}}

diff --git a/files/vi/web/javascript/reference/global_objects/string/replace/index.html b/files/vi/web/javascript/reference/global_objects/string/replace/index.html deleted file mode 100644 index b9d5330c6c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/replace/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: String.prototype.replace() -slug: Web/JavaScript/Reference/Global_Objects/String/replace -translation_of: Web/JavaScript/Reference/Global_Objects/String/replace ---- -
{{JSRef}}
- -

Phương thức replace() sẽ trả về một chuỗi mới với một vài (hoặc tất cả) phần tử trùng khớp với pattern được thay thế bằng replacement. Pattern có thể là một chuỗi, hoặc một {{jsxref("RegExp")}}, và replacement có thể là một chuỗi, hoặc một function được gọi áp dụng cho mỗi kết quả trùng khớp. Nếu pattern là một chuỗi, thì phương thức replace() chỉ trả về kết quả đầu tiên trùng khớp.

- -

Replace() không làm thay đổi chuỗi gốc.

- -
{{EmbedInteractiveExample("pages/js/string-replace.html")}}
- - - -

Cú pháp

- -
const newStr = str.replace(regexp|substr, newSubstr|function)
- -

Parameters

- -
-
regexp (pattern)
-
Một {{jsxref("RegExp")}} object hoặc biểu thức RegEx. Phần tử được match sẽ được thay thế bởi newSubstr hoặc giá trị trả về bởi function.
-
substr
-
Một {{jsxref("String")}} cái mà sẽ bị thay thế bởi newSubstr. String này sẽ được xem như là một literal string và không phải là một regular expression. Nên chỉ có phần tử trùng khớp đầu tiên sẽ bị thay thế.
-
newSubstr (replacement)
-
Một {{jsxref("String")}} có nhiệm vụ thay thế substr được chỉ định trong regexp hoặc substr. Có nhiều kiểu thay thế khác nhau, xem chi tiết tại phần "Specifying a string as a parameter" bên dưới.
-
function (replacement)
-
Function được định nghĩa và gọi để sử dụng cho việc thay thế các phần tử trùng khớp với regexp hoặc substr. Đối số của function này có thể là các loại sau, xem chi tiết tại phần: "Specifying a function as a parameter" bên dưới.
-
- -

Return value

- -

Một string mới, với một số phần tử trùng khớp (hoặc tất cả phần tử trùng khớp) đã bị thay thế bởi các replacement.

- -

Mô tả

- -

Phương thức này không làm thay đổi {{jsxref("String")}} gốc. Nó chỉ đơn giản tạo ra một string mới.

- -

Để thực hiện tìm kiếm global search và replace, hãy thêm từ khóa g và biểu thức regular expression.

- -

Specifying a string as a parameter

- -

The replacement string can include the following special replacement patterns:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nWhere n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is 1-indexed.
- -

Specifying a function as a parameter

- -

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: The above-mentioned special replacement patterns do not apply in this case.)

- -

Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

- -

The arguments to the function are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Possible nameSupplied value
matchThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth string found by a parenthesized capture group, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offsetThe offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
stringThe whole string being examined.
- -

(The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object—and, if so, how many parenthesized submatches it specifies.)

- -

The following example will set newString to 'abc - 12345 - #$*%':

- -
function replacer(match, p1, p2, p3, offset, string) {
-  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
-  return [p1, p2, p3].join(' - ');
-}
-let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
-console.log(newString);  // abc - 12345 - #$*%
-
- -

Ví dụ

- -

Định nghĩa một biểu thức regular expression trong phương thức replace()

- -

Ví dụ bên dưới, regular expression được định nghĩa trong replace() và nó có thêm flat "i" (giúp kết quả matching không phân biệt chữ hoa và chữ thường).

- -
let str = 'Twas the night before Xmas...';
-let newstr = str.replace(/xmas/i, 'Christmas');
-console.log(newstr);  // Twas the night before Christmas...
-
- -

This logs 'Twas the night before Christmas...'.

- -
-

Note: See this guide for more explanations about regular expressions.

-
- -

Sử dụng flag global và flag ignore trong replace()

- -

Global replace (thay thế tất cả kết quả trùng khớp) có thể được thực hiện trong regex. Ví dụ sau, biểu thức regex có chứa các flag  global and ignore case flags cho phép replace() sẽ thay thế mỗi string 'apples' trong chuỗi gốc với string 'oranges'

- -
let re = /apples/gi;
-let str = 'Apples are round, and apples are juicy.';
-let newstr = str.replace(re, 'oranges');
-console.log(newstr);  // oranges are round, and oranges are juicy.
-
- -

This logs 'oranges are round, and oranges are juicy'.

- -

Đảo ngược vị trí của 2 từ trong một string

- -

Đoạn code bên dưới sẽ đảo qua lại vị trí của các từ trong một string. Ở phần replacement, đoạn code sử dụng capturing groups và ký tự $1,$2 để làm pattern cho phần replacement.

- -
let re = /(\w+)\s(\w+)/;
-let str = 'John Smith';
-let newstr = str.replace(re, '$2, $1');
-console.log(newstr);  // Smith, John
-
- -

This logs 'Smith, John'.

- -

Sử dụng một inline function để thay đổi các giá trị matched

- -

Trong ví dụ này, tất cả trường hợp chữ cái viết hoa trong một string sẽ được convert sang dạng viết thường, và dấu gạch ngang sẽ được thêm vào trước vị trí matching đó. Điều quan trọng ở đây, là cần thêm vào các dấu gạch ngang này trước khi trả về một replacement hoàn chỉnh để sử dụng.

- -

Replacement function này sẽ nhận vào các đoạn trích mà đã match với pattern làm tham số, và sử dụng các đoạn trích đó để biến đổi chữ hoa chữ thường, và ghép nối một dấu gạch ngang vào trước mỗi đoạn trích.

- -
function styleHyphenFormat(propertyName) {
-  function upperToHyphenLower(match, offset, string) {
-    return (offset > 0 ? '-' : '') + match.toLowerCase();
-  }
-  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
-}
-
- -

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

- -

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.

- -
let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
-
- -

This is because '$&'.toLowerCase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern.

- -

Replacing a Fahrenheit degree with its Celsius equivalent

- -

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with "F". The function returns the Celsius number ending with "C". For example, if the input number is "212F", the function returns "100C". If the number is "0F", the function returns "-17.77777777777778C".

- -

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

- -
function f2c(x) {
-  function convert(str, p1, offset, s) {
-    return ((p1 - 32) * 5/9) + 'C';
-  }
-  let s = String(x);
-  let test = /(-?\d+(?:\.\d*)?)F\b/g;
-  return s.replace(test, convert);
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.replace")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/slice/index.html b/files/vi/web/javascript/reference/global_objects/string/slice/index.html deleted file mode 100644 index 002f1be65f..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/slice/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: String.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/String/slice -translation_of: Web/JavaScript/Reference/Global_Objects/String/slice ---- -
{{JSRef}}
- -

Phương thức slice() tạo ra một Chuỗi mới từ một phần của Chuỗi hiện tại.

- -

Cú pháp

- -
str.slice(beginSlice[, endSlice])
- -

Các tham số

- -
-
beginSlice
-
Chỉ số điểm bắt đầu của chuỗi con muốn lấy - bắt đầu từ 0. Nếu tham số này là số âm, thì nó tương đương với việc bạn gán nó bằng "độ dài chuỗi" + beginSlice. Ví dụ nếu beginSlice bằng -3 thì tương đương với beginSlice bằng "đội dài chuỗi" - 3.
-
endSlice
-
Tham số này không bắt buộc. Nếu có nó sẽ chỉ điểm cuối của chuỗi con muốn lấy. Nếu tham số này âm, nó sẽ được hiểu bằng "đội dài chuỗi" + endSlice. Ví dụ endSlice bằng -3 nó sẽ tương đương với "độ dài chuỗi" - 3
-
- -

Mô tả

- -

slice() thực hiện lấy một phần chuỗi từ chuỗi ban đầu và trả về một chuỗi mới. Chuỗi ban đầu sẽ không bị thay đổi giá trị.

- -

slice() sẽ lấy một phần chuỗi nhưng sẽ không chứa ký tự có chỉ số bằng với tham số endSlice. str.slice(1, 4) sẽ chỉ lấy ba ký tự 1,2 và 3.

- -

Ví dụ khác, str.slice(2, -1) sẽ lấy từ ký tự thứ 3 đến ký tự gần cuối, ký tự cuối không được đưa vào chuỗi mới

- -

Ví dụ

- -

Dùng slice() để tạo chuỗi mới

- -

Ví dụ sau sử dụng slice() để tạo chuỗi mới.

- -
var str1 = 'The morning is upon us.';
-var str2 = str1.slice(4, -2);
-
-console.log(str2); // OUTPUT: morning is upon u
-
- -

Dùng slice() với chỉ số âm

- -

Ví dụ sau sử dụng slice() với chỉ số âm.

- -
var str = 'The morning is upon us.';
-str.slice(-3);     // returns 'us.'
-str.slice(-3, -1); // returns 'us'
-str.slice(0, -1);  // returns 'The morning is upon us'
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tạTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}} 
- -

Khả năng hỗ trợ của các trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html b/files/vi/web/javascript/reference/global_objects/string/startswith/index.html deleted file mode 100644 index 7d3f6bfaa6..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: String.prototype.startsWith() -slug: Web/JavaScript/Reference/Global_Objects/String/startsWith -translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---- -
{{JSRef}}
- -

startsWith() method xác định liệu một chuỗi bắt đầu với các chữ cái của chuỗi khác hay không, trả về giá trị true hoặc false tương ứng.

- -

Cú pháp

- -
str.startsWith(searchString[, position])
- -

Tham số

- -
-
searchString
-
Các ký tự cần tìm kiếm tại vị trí bắt đầu của chuỗi này.
-
position
-
Tùy chọn. Vị trí trong chuỗi bắt đầu tìm kiếm cho searchString; mặc định là 0.
-
- -

Miêu tả

- -

Method này cho phép bạn xác định liệu một chuỗi có bắt đầu với chuỗi khác không.

- -

Ví dụ

- -

Cách sử dụng startsWith()

- -
var str = 'To be, or not to be, that is the question.';
-
-console.log(str.startsWith('To be'));         // true
-console.log(str.startsWith('not to be'));     // false
-console.log(str.startsWith('not to be', 10)); // true
-
- -

Polyfill

- -

Method này đã được thêm vào chỉ dẫn kỹ thuật ECMAScript 6 và có thể chưa có sẵn trong tất cả JavaScript implementations. Tuy nhiên, bạn có thể polyfill String.prototype.startWith() với snippet sau:

- -
if (!String.prototype.startsWith) {
-  String.prototype.startsWith = function(searchString, position) {
-    position = position || 0;
-    return this.indexOf(searchString, position) === position;
-  };
-}
-
- -

Polyfill mạnh và được tối ưu hơn có sẵn trên GitHub bởi Mathias Bynens.

- -

Hướng dẫn kỹ thuật

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES6')}}Initial definition.
- -

Khả năng tương thích với Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatChrome("41")}}{{CompatSafari("9")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/substr/index.html b/files/vi/web/javascript/reference/global_objects/string/substr/index.html deleted file mode 100644 index c7d477fede..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substr/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.substr() -slug: Web/JavaScript/Reference/Global_Objects/String/substr -translation_of: Web/JavaScript/Reference/Global_Objects/String/substr ---- -
{{JSRef}}
- -
Phương thức substr()trả  về những ký tự trong một chuỗi được xác định bởi vị trí ký tự bắt đầu và số lượng ký tự theo sau đó.
- -

Cú pháp

- -
str.substr(start, [length])
- -

Các tham số

- -
-
start (bắt đầu)
-
Vị trí chính xác của ký tự bắt đầu. Nếu là một số âm, nó sẽ được xử lý như sau strLength - start trong đó strLengthlà chiều dài của chuỗi. Ví dụ, str.substr(-3) sẽ được coi như là str.substr(str.length -3)
-
length (độ dài)
-
Số lượng ký tự muốn lấy ra. Nếu tham số này là {{jsxref("undefined")}}, tất cả các ký tự từ vị trí bắt đầu tới kết thúc của chuỗi sẽ được lấy.
-
- -

Giá trị trả về

- -

Một chuỗi mới là phần đã lấy ra từ chuỗi ban đầu. Nếu  length là 0 hoặc là một số âm thì trả về một chuỗi rỗng.

- -

Mô tả

- -

start là chỉ số của ký tự. Chỉ số của ký tự đầu tiên là 0, và chỉ số của ký tự cuối cùng thì nhỏ hơn độ dài của chuỗi là 1. substr() bắt đầu lấy các ký tự tại start  và thu thập length các ký tự( trừ khi nó chấm tới cuối chuỗi trước, trong trường hợp này nó sẽ trả về ít hơn).

- -

Nếu start là số dương và lớn hơn hoặc bằng chiều dài của chuỗi, substr() trả về một chuỗi rỗng.

- -

Nếu start là số âm, substr() coi nó như chỉ là chỉ số của ký tự tính từ cuối chuỗi; chỉ số của ký tự cuối cùng là -1. Nếu  start là số âm và abs(start) lớn hơn chiều dài của chuỗi,substr() coi 0 như là chỉ số bắt đầu.

- -

Chú ý: Việc xử lý giá trị âm của tham số start như ở trên không được Microsoft JScript hỗ trợ.

- -

Nếu length là 0 hoặc âm, substr() trả về một mảng rỗng. Nếu length bị bỏ sót, substr() lấy các ký tự cho tới cuối chuỗi.

- -

Ví dụ

- -

Sử dụng substr()

- -
var str = 'abcdefghij';
-
-console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
-console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
-console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
-console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
-console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
-console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '
-
- -

Polyfill

- -

Microsoft's JScript không hỗ trợ các giá trị âm cho chi số bắt đầu. Nếu bạn mong muốn sử dụng tính năng này, bạn có thể sử dụng đoạn code dưới đây để xử lý bug này:

- -
// only run when the substr() function is broken
-if ('ab'.substr(-1) != 'b') {
-  /**
-   *  Get the substring of a string
-   *  @param  {integer}  start   where to start the substring
-   *  @param  {integer}  length  how many characters to return
-   *  @return {string}
-   */
-  String.prototype.substr = function(substr) {
-    return function(start, length) {
-      // call the original method
-      return substr.call(this,
-      	// did we get a negative start, calculate how much it is from the beginning of the string
-        // adjust the start parameter for negative value
-        start < 0 ? this.length + start : start,
-        length)
-    }
-  }(String.prototype.substr);
-}
-
- -

Các quy cách

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Quy cáchTình trạngÝ kiến
{{SpecName('ES3')}}{{Spec2('ES3')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). Ap dung trong JavaScript 1.0
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). 
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ESDraft')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
- -

Tương thích với trình duyệt

- - - -

{{Compat("javascript.builtins.String.substr")}}

- -

Tương tự

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/substring/index.html b/files/vi/web/javascript/reference/global_objects/string/substring/index.html deleted file mode 100644 index e53b920581..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substring/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: String.prototype.substring() -slug: Web/JavaScript/Reference/Global_Objects/String/substring -translation_of: Web/JavaScript/Reference/Global_Objects/String/substring ---- -
{{JSRef}}
- -

substring() phương thức trả về chuỗi con của 1 chuỗi bắt đầu từ vị trí bắt đầu đến vị trí kết thúc, hoặc đến cuối chuỗi nếu không có vị trí kết thúc

- -

Cú pháp

- -
str.substring(indexStart[, indexEnd])
- -

Parameters

- -
-
indexStart
-
Một số integer giữa 0 và một số nhỏ hơn độ dài chuỗi, xác định vị trí kí tự đầu tiên trong chuỗi gốc để đưa vào chuỗi con.
-
indexEnd
-
Không bắt buộc. Một số integer giữa 0 và độ dài chuỗi. Chuỗi con không bao gồm ký tự ở vị trí indexEnd.
-
- -

Return value

- -

Chuỗi con trả về là chuỗi nằm ở vị trí từ indexStart đến vị trí ( indexEnd - 1 )

- -

Description

- -

substring() lấy ký tự từ vị trí indexStart tới vị trí (nhưng không bao gồm) indexEnd. Đặc biệt:

- - - -

Nếu indexStart lớn hơn indexEnd, chúng se được đổi chỗ; ví dụ, str.substring(1, 0) == str.substring(0, 1).

- -

Examples

- -

Using substring()

- -

The following example uses substring() to display characters from the string 'Mozilla':

- -
var anyString = 'Mozilla';
-
-// Displays 'Moz'
-console.log(anyString.substring(0, 3));
-console.log(anyString.substring(3, 0));
-
-// Displays 'lla'
-console.log(anyString.substring(4, 7));
-console.log(anyString.substring(4));
-console.log(anyString.substring(7, 4));
-
-// Displays 'Mozill'
-console.log(anyString.substring(0, 6));
-
-// Displays 'Mozilla'
-console.log(anyString.substring(0, 7));
-console.log(anyString.substring(0, 10));
-
- -

Using substring() with length property

- -

The following example uses the substring() method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

- -
// Displays 'illa' the last 4 characters
-var anyString = 'Mozilla';
-var anyString4 = anyString.substring(anyString.length - 4);
-console.log(anyString4);
-
-// Displays 'zilla' the last 5 characters
-var anyString = 'Mozilla';
-var anyString5 = anyString.substring(anyString.length - 5);
-console.log(anyString5);
-
- -

Replacing a substring within a string

- -

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string 'Brave New World' into 'Brave New Web'.

- -
// Replaces oldS with newS in the string fullS
-function replaceString(oldS, newS, fullS) {
-  for (var i = 0; i < fullS.length; ++i) {
-    if (fullS.substring(i, i + oldS.length) == oldS) {
-      fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
-    }
-  }
-  return fullS;
-}
-
-replaceString('World', 'Web', 'Brave New World');
-
- -

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

- -
function replaceString(oldS, newS, fullS) {
-  return fullS.split(oldS).join(newS);
-}
-
- -

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - -- cgit v1.2.3-54-g00ecf