String

翻译正在进行中。

String 全局对象是用来构造字符串的构造函数。

语法

通常,我们都使用字符串的字面量写法,如下所示:

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

除了普通的可打印字符以外,一些特殊的字符可以通过其转义形式放入字符串中:

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

你还可以使用 String 函数来将其他值生成或转换成字符串:

String(thing)
new String(thing)

参数

thing
任何可以被转换成字符串的值。

描述

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 length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf method, or extracting substrings with the substring method.

单个字符访问

There are two ways to access an individual character in a string. The first is the 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 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.

对字符串primitives和 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
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.

属性

String.prototype
Allows the addition of properties to a String object.

方法

String.fromCharCode()

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.
Properties inherited from Object:

跟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)

 

相关链接

文档标签和贡献者

标签: 
向此页面作出贡献: lunix01, FredWe, teoli, ziyunfei
最后编辑者: lunix01,
隐藏侧边栏