| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.
* Some parts of this feature may have varying levels of support.
String
'string text' "string text" " espaol deutsch English portugus "
String
String(thing)
ECMAScript 2015Template 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
return "cat".charAt(1); // "a"
( ECMAScript 5 )
return "cat"[1]; // "a"
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 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
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 instancesString.prototype.lengthReflects the length of the string. Read-only.
String.prototype.at()Returns the character (exactly one UTF-16 code unit) at the specified index. 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 specified
index.
String.prototype.charCodeAt()Returns a number that is the UTF-16 code unit value at the given
index.
String.prototype.codePointAt()Returns a nonnegative integer Number that is the code point value of the UTF-16
encoded code point starting at the specified pos.
String.prototype.concat()Combines the text of two (or more) strings and returns a new string.
String.prototype.includes()Determines whether the calling string contains searchString.
String.prototype.endsWith()Determines whether a string ends with the characters of the string
searchString.
String.prototype.indexOf()Returns the index within the calling String object of the first
occurrence of searchValue, or -1 if not found.
String.prototype.lastIndexOf()Returns the index within the calling String object of the last
occurrence of searchValue, or -1 if not found.
String.prototype.localeCompare()Returns a number indicating whether the reference string
compareString comes before, after, or is equivalent to the
given string in sort order.
String.prototype.match()Used to match regular expression regexp against a string.
String.prototype.matchAll()Returns an iterator of all regexp'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 of
the length targetLength.
String.prototype.padStart()Pads the current string from the start with a given string and returns a new string
of the length targetLength.
String.prototype.repeat()Returns a string consisting of the elements of the object repeated
count times.
String.prototype.replace()Used to replace occurrences of searchFor using
replaceWith. searchFor may be a string
or Regular Expression, and replaceWith may be a string or
function.
String.prototype.replaceAll()Used to replace all occurrences of searchFor using
replaceWith. searchFor may be a string
or Regular Expression, and replaceWith may be a string or
function.
String.prototype.search()Search for a match between a regular expression regexp and
the 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 occurrences
of the substring sep.
String.prototype.startsWith()Determines whether the calling string begins with the characters of string
searchString.
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 the current locale.
For most languages, this will return the same as
toLowerCase().
String.prototype.toLocaleUpperCase( [locale, ...locales])The characters within a string are converted to uppercase 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 lowercase.
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.
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 the
Object.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.
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]));
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-string-objects |
This page was last modified on 2026526 by MDN contributors.
Stringanchor()at()big()blink()bold()charAt()charCodeAt()codePointAt()String.prototype.concat()endsWith()fixed()fontcolor()fontsize()includes()indexOf()isWellFormed()italics()lastIndexOf()link()String.prototype.localeCompare()match()matchAll()normalize()padEnd()String.prototype.padStart()repeat()replace()replaceAll()search()slice()small()split()startsWith()strike()sub()substr()substring()sup()toLocaleLowerCase()toLocaleUpperCase()String.prototype.toLowerCase()toString()toUpperCase()toWellFormed()String.prototype.trim()trimEnd()trimStart()valueOf()[Symbol.iterator]()Object/FunctionYour blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |