翻译正在进行中。
String
全局对象是用来构造字符串的构造函数。
语法
通常,我们都使用字符串的字面量写法,如下所示:
'string text' "string text" "中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어"
你还可以使用 String
函数来将其他值生成或转换成字符串:
String(thing) new String(thing)
参数
thing
- 任何可以被转换成字符串的值。
模板字符串
从ECMAScript 2015开始,字符串字面量也可以称为模板字符串:
`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`
转义字符
除了普通的可打印字符以外,一些特殊的字符可以通过其转义形式放入字符串中:
Code | Output |
---|---|
\0 |
the NUL 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 |
\xXX |
the Latin-1 character |
注意:和其他语言不同,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.";
这两种方式会创建相同的字符串。
描述
字符串对于保存可以以文本形式表示的数据非常有用。 一些常用的字符串操作符有:查询字符串长度,使用 + 和 += 字符串运算符来构建和连接字符串,检查字符串的存在或位置使用indexOf方法或使用substring方法提取子字符串。
单个字符访问
获取字符串的某一单个字符有两种方法。 第一种是使用 charAt
方法:
return 'cat'.charAt(1); // returns "a"
另一种方法 (在ECMAScript 5中有所介绍) 是把字符串当作一个类数组对象,其中的每个字符对应一个数值索引:
return 'cat'[1]; // returns "a"
使用括号访问字符串不可以对其进行删除或添加,因为对应属性并不是可读或可写的。 (See Object.defineProperty
for more information.)
字符串比较
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 print(a + " is less than " + b); else if (a > b) print(a + " is greater than " + b); else print(a + " and " + b + " are equal.");
A similar result can be achieved using the localeCompare
method inherited by String
instances.
对原始字符串和 String
对象的区分
Note that JavaScript distinguishes between String
objects and primitive string values. (The same is true of Boolean
and 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); // Logs "string" console.log(typeof s_obj); // Logs "object"
String primitives and String
objects also give different results when using 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:
s1 = "2 + 2"; // creates a string primitive 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 valueOf
method.
console.log(eval(s2.valueOf())); // returns the number 4
StringView
– a C-like representation of strings based on typed arrays.属性
String.prototype
- Allows the addition of properties to a
String
object.
方法
- Returns a string created by using the specified sequence of Unicode values.
String.fromCodePoint()
- Returns a string created by using the specified sequence of code points.
String.raw()
- Returns a string created from a raw template string.
String
generic methods
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; console.log(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
实例
属性
String.prototype.constructor
- 用于创造对象的原型对象的特定的函数。
String.prototype.length
- 返回了字符串的长度。
- 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.
跟HTML无关的方法
String.prototype.charAt()
- 返回字符的特定位置。
String.prototype.charCodeAt()
- 返回表示给定索引的字符的Unicode的值。
String.prototype.codePointAt()
- 返回使用UTF-16编码的给定位置的值的非负整数。
String.prototype.concat()
- 连接两个字符串文本,并返回一个新的字符串。
String.prototype.contains()
- 判断一个字符串里是否包含其他字符串。
String.prototype.endsWith()
- 判断一个字符串的结尾是否包含其他字符串中的字符。
String.prototype.indexOf()
- 从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。
String.prototype.lastIndexOf()
- 从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。
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()
- 使用正则表达式与字符串相比较。
String.prototype.normalize()
- 返回调用字符串值的Unicode标准化形式。
String.prototype.quote()
- Wraps the string in double quotes ("
"
"). String.prototype.repeat()
- 返回指定重复次数的由元素组成的字符串对象。
String.prototype.replace()
- 被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。
String.prototype.search()
- 对正则表达式和指定字符串进行匹配搜索,返回第一个出现的匹配项的下标。
String.prototype.slice()
- 摘取一个字符串区域,返回一个新的字符串。
String.prototype.split()
- 通过分离字符串成字串,将字符串对象分割成字符串数组。
String.prototype.startsWith()
- 判断字符串的起始位置是否匹配其他字符串中的字符。
String.prototype.substr()
- Returns the characters in a string beginning at the specified location through the specified number of characters.
String.prototype.substring()
- 返回在字符串中指定另个下标之间的字符。
String.prototype.toLocaleLowerCase()
- 根据当前区域设置,将符串中的字符转换成小写。对于大多数语言来说,
toLowerCase
的返回值是一致的。 String.prototype.toLocaleUpperCase()
- 根据当前区域设置,将字符串中的字符转换成大写,对于大多数语言来说,
toUpperCase
的返回值是一致的。 String.prototype.toLowerCase()
- 将字符串转换成小写并返回。
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()
- 返回用字符串表示的特定对象。重写
Object.prototype.toString
方法。 String.prototype.toUpperCase()
- 将字符串转换成大写并返回。
String.prototype.trim()
- 从字符串的开始和结尾去除空格。参照部分 ECMAScript 5 标准。
String.prototype.trimLeft()
- 从字符串的左侧去除空格。
String.prototype.trimRight()
- 从字符串的右侧去除空格。
String.prototype.valueOf()
- 返回特定对象的原始值。重写
Object.prototype.valueOf
方法。
HTML wrapper methods
下面的方法被限制使用,因为只对可用的HTML表情和属性提供部分支持。
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>
示例
将其他值转换成字符串
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 | Status | Comment |
---|---|---|
ECMAScript 1st Edition. | Standard | Initial definition. |
ECMAScript 5.1 (ECMA-262) String |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) String |
Standard |
浏览器兼容性
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) |