String 全局对象是一个用于字符串或一个字符序列的构造函数。

语法

字符串字面量采取以下形式:

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

你也能使用 String 函数将其他值生成或转换成字符串:

  • String(thing)
  • new String(thing)

    参数

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

    模板字面量

从 ECMAScript 2015 开始,字符串字面量也可以称为模板字面量

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

转义字符

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

Code Output
\0 空字符
\' 单引号
\" 双引号
\\ 反斜杠
\n 换行
\r 回车
\v 垂直制表符
\t 水平制表符
\b 退格
\f 换页
\uXXXX unicode 码
\u{X}\u{XXXXXX} unicode codepoint
\xXX Latin-1 字符(x小写)

和其他语言不同,javascript 的字符串不区分单引号和双引号,所以不论是单引号还是双引号的字符串,上面的转义字符都能运行 。

长字符串

有时,你的代码可能含有很长的字符串。你可能想将这样的字符串写成多行,而不是让这一行无限延长或着被编辑器折叠。有两种方法可以做到这一点。
其一,可以使用 + 运算符将多个字符串连接起来,如下所示:

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

其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示:

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

使用这两种方式会创建相同的字符串。

描述

字符串对于保存可以以文本形式表示的数据非常有用。 一些常用的字符串操作有:查询字符串长度,使用 + 和 += 运算符来构建和连接字符串,使用 indexOf 方法检查某一子字符串在父字符串中的位置,又或是使用 substring 方法提取从父字符串中提取子字符串。

从字符串中获取单个字符

获取字符串的某个字符有两种方法。 第一种是使用 charAt 方法:

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

另一种 (在ECMAScript 5中有所介绍) 是把字符串当作一个类似数组的对象,其中的每个字符对应一个数值索引:

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

使用括号访问字符串不可以对其进行删除或添加,因为字符串对应未知的属性并不是可读或配置的。 (更多的信息请参阅 Object.defineProperty。 )

字符串比较

熟练使用 C 语言的开发者经常使用 strcmp 函数来比较字符串,但在 JavaScript 中,你只需要使用比较操作符(>/</>=/<=)

字符串比较则是使用基于标准字典的 Unicode 值来进行比较的。

  1. var a = "a";
  2. var b = "b";
  3. if (a < b) // true
  4. console.log(a + " is less than " + b);
  5. else if (a > b)
  6. console.log(a + " is greater than " + b);
  7. else
  8. console.log(a + " and " + b + " are equal.");

使用从字符串实例继承而来的 localeCompare 方法也能达到同样的效果。

基本字符串和字符串对象的区别

请注意区分 JavaScript 字符串对象和基本字符串值 . ( 对于 BooleanNumbers 也同样如此.)

  • 字符串字面量 (通过单引号或双引号定义) 和 直接调用 String 方法(没有通过 new 生成字符串对象实例)的字符串都是基本字符串。
  • JavaScript会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象之后才可以使用字符串对象的方法。
  • 当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候(基本字符串是没有这些方法的),JavaScript 会自动将基本字符串转化为字符串对象并且调用相应的方法或者执行查询。
    1. var s_prim = "foo";
    2. var s_obj = new String(s_prim);
    3. console.log(typeof s_prim); // Logs "string"
    4. console.log(typeof s_obj); // Logs "object"

当使用 eval时,基本字符串和字符串对象也会产生不同的结果。eval 会将基本字符串作为源代码处理; 而字符串对象则被看作对象处理, 返回对象。 例如:

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

由于上述原因, 当一段代码在需要使用基本字符串的时候却使用了字符串对象就会导致执行失败(虽然一般情况下程序员们并不需要考虑这样的问题)。

利用 valueOf 方法,我们可以将字符串对象转换为其对应的基本字符串。

  1. console.log(eval(s2.valueOf())); // returns the number 4

注意: 其他的将字符串对象转换成基本字符串的方法可以及参考 StringView – a C-like representation of strings based on typed arrays.

属性

[String.prototype](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/prototype) 可以为 String 对象增加新的属性。
**String.prototype** 属性表示 String原型对象。

String.prototype 属性的属性特性:
writable false
enumerable false
configurable false

所有 String 的实例都继承自 String.prototype. 任何String.prototype上的改变都会影响到所有的 String 实例。

  • String.prototype.constructor
    • 用于创造对象的原型对象的特定的函数。
  • [String.prototype.length](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/length)
    • 返回了字符串的长度。
  • N
    • 用于访问第N个位置的字符,其中N是小于 length 和 0之间的正整数。这些属性都是“只读”性质,不能编辑。

方法

通过一串 Unicode 创建字符串。

String.fromCharCode()
返回由指定的 UTF-16 代码单元序列创建的字符串。

  1. console.log(String.fromCharCode(189, 43, 190, 61));
  2. // expected output: "½+¾="

通过一串 码点 创建字符串。

实验性API,尽量不要在生产环境中使用
String.fromCodePoint()
返回使用指定的代码点序列创建的字符串。

  1. console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
  2. // expected output: "☃★♲你"

通过模板字符串创建字符串。

实验性API,尽量不要在生产环境中使用
String.raw()

在大多数情况下, String.raw()是用来处理模版字符串的. 不要被上面复杂的参数要求吓到,因为像所有的 tag functions一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。
String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。

  1. String.raw`Hi\n${2+3}!`;
  2. // 'Hi\n5!',Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
  3. String.raw `Hi\u000A!`;
  4. // "Hi\u000A!",同上,这里得到的会是 \、u、0、0、0、A 6个字符,
  5. // 任何类型的转义形式都会失效,保留原样输出,不信你试试.length
  6. let name = "Bob";
  7. String.raw `Hi\n${name}!`;
  8. // "Hi\nBob!",内插表达式还可以正常运行
  9. // 正常情况下,你也许不需要将 String.raw() 当作函数调用。
  10. // 但是为了模拟 `t${0}e${1}s${2}t` 你可以这样做:
  11. String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
  12. // 注意这个测试, 传入一个 string, 和一个类似数组的对象
  13. // 下面这个函数和 `foo${2 + 3}bar${'Java' + 'Script'}baz` 是相等的.
  14. String.raw({
  15. raw: ['foo', 'bar', 'baz']
  16. }, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'

语法:
参数:
返回值:

String 实例

跟HTML无关的方法

返回特定位置的字符。

String.prototype.charAt()
charAt() 方法从一个字符串中返回指定的字符。
语法:str.charAt(index)
参数:

  • index
    • 一个介于0 和字符串长度减1之间的整数。 (0~length-1)
    • 如果没有提供索引,charAt() 将使用0。

返回值:
说明:
字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。 如果指定的 index 值超出了该范围,则返回一个空字符串。
示例:
下例输出字符串 “Brave new world“ 不同位置处的字符:

  1. var anyString = "Brave new world";
  2. // The character at index 0 is 'B'
  3. console.log("The character at index 0 is '" + anyString.charAt(0) + "'");
  4. // The character at index 1 is 'r'
  5. console.log("The character at index 1 is '" + anyString.charAt(1) + "'");
  6. // The character at index 2 is 'a'
  7. console.log("The character at index 2 is '" + anyString.charAt(2) + "'");
  8. // The character at index 3 is 'v'
  9. console.log("The character at index 3 is '" + anyString.charAt(3) + "'");
  10. // The character at index 4 is 'e'
  11. console.log("The character at index 4 is '" + anyString.charAt(4) + "'");
  12. // The character at index 999 is ''
  13. console.log("The character at index 999 is '" + anyString.charAt(999) + "'");

返回表示给定索引的字符的Unicode的值。

String.prototype.charCodeAt()
**charCodeAt()** 方法返回 065535 之间的整数,表示给定索引处的 UTF-16 代码单元。
UTF-16 编码单元匹配能用一个 UTF-16 编码单元表示的 Unicode 码点。如果 Unicode 码点不能用一个 UTF-16 编码单元表示(因为它的值大于0xFFFF),则所返回的编码单元会是这个码点代理对的第一个编码单元) 。如果你想要整个码点的值,使用 codePointAt()
语法:str.charCodeAt(index)
参数:

  • index
    • 一个大于等于 0,小于字符串长度的整数。如果不是一个数值,则默认为 0

返回值:指定 index 处字符的 UTF-16 代码单元值的一个数字;如果 index 超出范围,charCodeAt() 返回 NaN

Unicode 码点(code points)的范围从 01114111 (0x10FFFF)。开头的 128 个 Unicode 编码单元和 ASCII 字符编码一样。(关于 Unicode 的更多信息,可查看 JavaScript Guide。)

注意:charCodeAt 总是返回一个小于 65,536 的值。这是因为高位编码单元(higher code point)使用一对(低位编码 lower valued)代理伪字符(”surrogate” pseudo-characters)来表示,从而构成一个真正的字符。

因此,为了检查(或重现)65536 及以上编码字符的完整字符,需要在获取 charCodeAt(i) 的值的同时获取 charCodeAt(i+1) 的值(如同用两个字母操纵一个字符串),或者改为获取 codePointAt(i) 的值。参看下面例 2 和例 3。

如果指定的 index 小于 0 、等于或大于字符串的长度,则 charCodeAt 返回 NaN

示例:

  1. const sentence = 'The quick brown fox jumps over the lazy dog.';
  2. const index = 4;
  3. console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`);
  4. // expected output: "The character code 113 is equal to q"
  5. "ABC".charCodeAt(0) // returns 65:"A"
  6. "ABC".charCodeAt(1) // returns 66:"B"
  7. "ABC".charCodeAt(2) // returns 67:"C"
  8. "ABC".charCodeAt(3) // returns NaN

返回使用UTF-16编码的给定位置的值的非负整数

String.prototype.codePointAt()
codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。
语法:str.codePointAt(pos)
参数:

  • pos
    • 这个字符串中需要转码的元素的位置。

返回值:返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 undefined

示例:

  1. 'ABC'.codePointAt(1); // 66
  2. '\uD800\uDC00'.codePointAt(0); // 65536
  3. 'XYZ'.codePointAt(42); // undefined

连接两个字符串文本

String.prototype.concat()
concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。
语法:str.concat(str2, [, ...strN])
参数:

  • str2 [, ...strN]
    • 需要连接到 str 的字符串。

返回值:一个新的字符串,包含参数所提供的连接字符串。
concat 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。 concat 方法并不影响原字符串。
如果参数不是字符串类型,它们在连接之前将会被转换成字符串。

示例:

  1. let hello = 'Hello, '
  2. console.log(hello.concat('Kevin', '. Have a nice day.'))
  3. // Hello, Kevin. Have a nice day.
  4. let greetList = ['Hello', ' ', 'Venkat', '!']
  5. "".concat(...greetList) // "Hello Venkat!"
  6. "".concat({}) // [object Object]
  7. "".concat([]) // ""
  8. "".concat(null) // "null"
  9. "".concat(true) // "true"
  10. "".concat(4, 5) // "45"

判断一个字符串里是否包含其他字符串

String.prototype.includes()
includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。
includes() 方法是区分大小写的。
语法:str.includes(searchString[, position])
参数:

  • searchString
    • 要在此字符串中搜索的字符串。
  • position 可选
    • 从当前字符串的哪个索引位置开始搜寻子字符串,默认值为 0

返回值:如果当前字符串包含被搜寻的字符串,就返回 true;否则返回 false

  1. var str = 'To be, or not to be, that is the question.';
  2. console.log(str.includes('To be')); // true
  3. console.log(str.includes('question')); // true
  4. console.log(str.includes('nonexistent')); // false
  5. console.log(str.includes('To be', 1)); // false 从1索引开始查找
  6. console.log(str.includes('TO BE')); // false

兼容补丁

这个方法已经被加入到 ECMAScript 6 标准中,但未必在所有的 JavaScript 实现中都可以使用。然而,你可以轻松地 polyfill 这个方法:

  1. if (!String.prototype.includes) {
  2. String.prototype.includes = function(search, start) {
  3. 'use strict';
  4. if (typeof start !== 'number') {
  5. start = 0;
  6. }
  7. if (start + search.length > this.length) {
  8. return false;
  9. } else {
  10. return this.indexOf(search, start) !== -1;
  11. }
  12. };
  13. }

判断一个字符串的是否以给定字符串结尾

String.prototype.endsWith()
**endsWith()**方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 truefalse
语法:str.endsWith(searchString[, length])
参数:

  • searchString
    • 要搜索的子字符串。
  • length 可选
    • 作为 str 的长度。默认值为 str.length

返回值:如果传入的子字符串在搜索字符串的末尾则返回true;否则将返回 false
这个方法帮助你确定一个字符串是否在另一个字符串的末尾。这个方法是大小写敏感的。

  1. var str = "To be, or not to be, that is the question.";
  2. alert( str.endsWith("question.") ); // true
  3. alert( str.endsWith("to be") ); // false
  4. alert( str.endsWith("to be", 19) ); // true 19:str的长度,默认值为 str.length。

兼容

这个方法已经加入到 ECMAScript 6 标准当中,但是可能还没有在所有的 JavaScript 实现中可用。然而,你可以通过如下的代码片段扩展 String.prototype.endsWith() 实现兼容:

  1. if (!String.prototype.endsWith) {
  2. String.prototype.endsWith = function(search, this_len) {
  3. if (this_len === undefined || this_len > this.length) {
  4. this_len = this.length;
  5. }
  6. return this.substring(this_len - search.length, this_len) === search;
  7. };
  8. }

indexOf() 和 lastIndexOf()

indexOf()

String.prototype.indexOf()从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。

语法:str.indexOf(searchValue [, fromIndex])
参数:

  • searchValue :
    • 要被查找的字符串值。
    • 如果没有提供确切地提供字符串,searchValue 会被强制设置为 “undefined”, 然后在当前字符串中查找这个值。
    • 举个例子:’undefined’.indexOf() 将会返回0,因为 undefined 在位置0处被找到,但是’undefine’.indexOf() 将会返回 -1 ,因为字符串 ‘undefined’ 未被找到。
  • fromIndex | 可选
    • 数字表示开始查找的位置。可以是任意整数,默认值为 0。
    • 如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。( fromIndex 的值小于 0,等同于为空情况; fromIndex 的值大于 str.length ,那么结果会直接返回 -1 。)
    • 举个例子,’hello world’.indexOf(‘o’, -5) 返回 4 ,因为它是从位置0处开始查找,然后 o 在位置4处被找到。另一方面,’hello world’.indexOf(‘o’, 11) (或 fromIndex 填入任何大于11的值)将会返回 -1 ,因为开始查找的位置11处,已经是这个字符串的结尾了。

返回值:查找的字符串 searchValue 的第一次出现的索引,如果没有找到,则返回 -1

若被查找的字符串 searchValue 是一个空字符串,将会产生“奇怪”的结果。如果 fromIndex 值为空,或者 fromIndex 值小于被查找的字符串的长度,返回值和以下的 fromIndex 值一样:

  1. 'hello world'.indexOf('') // 返回 0
  2. 'hello world'.indexOf('', 0) // 返回 0
  3. 'hello world'.indexOf('', 3) // 返回 3
  4. 'hello world'.indexOf('', 8) // 返回 8

另外,如果 fromIndex 值大于等于字符串的长度,将会直接返回字符串的长度(str.length):

  1. 'hello world'.indexOf('', 11) // 返回 11
  2. 'hello world'.indexOf('', 13) // 返回 11
  3. 'hello world'.indexOf('', 22) // 返回 11

从前面一个例子可以看出,被查找的值是空值时,Javascript将直接返回指定的索引值。从后面一个例子可以看出,被查找的值是空值时,Javascript将直接返回字符串的长度。

lastIndexOf()

String.prototype.lastIndexOf()从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。

语法:str.lastIndexOf(searchValue[, fromIndex])
参数:

  • searchValue :
    • 一个字符串,表示被查找的值。如果searchValue是空字符串,则返回fromIndex。
  • fromIndex | 可选
    • 待匹配字符串searchValue的开头一位字符从 str的第fromIndex位开始向左回向查找。fromIndex默认值是 +Infinity。如果 fromIndex >= str.length ,则会搜索整个字符串。如果 fromIndex < 0 ,则等同于 fromIndex == 0。

返回值:返回指定值最后一次出现的索引(该索引仍是以从左至右0开始记数的),如果没找到则返回-1。

应用

字符串中的字符被从左向右索引。第一个字符的索引(index)是 0,变量名为 stringName 的字符串的最后一个字符的索引是 stringName.length - 1 。

  1. "Blue Whale".indexOf("Blue") // 返回 0
  2. "Blue Whale".indexOf("Blute") // 返回 -1
  3. "Blue Whale".indexOf("Whale", 0) // 返回 5
  4. "Blue Whale".indexOf("Whale", 5) // 返回 5
  5. "Blue Whale".indexOf("", -1) // 返回 0
  6. "Blue Whale".indexOf("", 9) // 返回 9
  7. "Blue Whale".indexOf("", 10) // 返回 10
  8. "Blue Whale".indexOf("", 11) // 返回 10

indexOf 方法是区分大小写的。例如,下面的表达式将返回 -1

  1. "Blue Whale".indexOf("blue") // 返回 -1

检测是否存在某字符串

注意 0 并不会被当成 true-1 不会被当成 false 。所以当检测某个字符串是否存在于另一个字符串中时,可使用下面的方法:

  1. 'Blue Whale'.indexOf('Blue') !== -1 // true
  2. 'Blue Whale'.indexOf('Bloe') !== -1 // false
  3. ~('Blue Whale'.indexOf('Bloe')) // 0, 这是一种错误用法

使用 indexOf 统计一个字符串中某个字母出现的次数

在下例中,设置了 count 来记录字母 e 在字符串 str 中出现的次数:

  1. // 翻译:生存还是毁灭?这是个问题。(莎士比亚《哈姆雷特》)
  2. var str = 'To be, or not to be, that is the question.';
  3. var count = 0;
  4. var pos = str.indexOf('e');
  5. while (pos !== -1) {
  6. count++;
  7. pos = str.indexOf('e', pos + 1);
  8. }
  9. console.log(count); // displays 4

使用indexOf() 和 lastIndexOf()

下例使用 indexOf()lastIndexOf() 方法定位字符串中 “Brave new world“ 的值。

  1. var anyString = "Brave new world";
  2. console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
  3. // logs 8
  4. console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
  5. // logs 10
  6. console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
  7. // logs 6
  8. console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
  9. // logs 6

指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。

String.prototype.localeCompare()
localeCompare() 方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。
语法: referenceStr.localeCompare(compareString[, locales[, options]])
参数:
image.png
image.png
image.png
image.png
返回值:如果引用字符存在于比较字符之前则为负数; 如果引用字符存在于比较字符之后则为正数; 相等的时候返回 0 .

描述

返回一个数字表示是否 引用字符串 在排序中位于 比较字符串 的前面,后面,或者二者相同。

  • 引用字符串 比较字符串 前面时返回 -1
  • 引用字符串比较字符串 后面时返回 1
  • 相同位置时返回 0

切勿依赖于 -1 或 1 这样特定的返回值。不同浏览器之间(以及不同浏览器版本之间) 返回的正负数的值各有不同,因为W3C规范中只要求返回值是正值和负值,而没有规定具体的值。一些浏览器可能返回-2或2或其他一些负的、正的值。

  1. // The letter "a" is before "c" yielding a negative value
  2. 'a'.localeCompare('c');
  3. // -2 or -1 (or some other negative value)
  4. // Alphabetically the word "check" comes after "against" yielding a positive value
  5. 'check'.localeCompare('against');
  6. // 2 or 1 (or some other positive value)
  7. // "a" and "a" are equivalent yielding a neutral value of zero
  8. 'a'.localeCompare('a');
  9. // 0

当比较大量字符串时, 比如比较大量数组时, 最好创建一个Intl.Collator 对象并使用compare 属性所提供的函数。

使用正则表达式与字符串相比较

String.prototype.match()使用正则表达式与字符串相比较。返回一个字符串匹配正则表达式的结果。
语法:str.match(regexp)
参数:regexp :一个正则表达式对象。如果传入一个非正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。如果你没有给出任何参数并直接使用match() 方法 ,你将会得到一 个包含空字符串的 Array :[“”] 。
返回值:

  • 如果使用g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。
  • 如果未使用g标志,则仅返回第一个完整匹配及其相关的捕获组(Array)。 在这种情况下,返回的项目将具有如下所述的其他属性。

    附加属性

    如上所述,匹配的结果包含如下所述的附加特性。

  • groups: 一个捕获组数组 或 undefined(如果没有定义命名捕获组)。

  • index: 匹配的结果的开始位置
  • input: 搜索的字符串.

一个Array,其内容取决于global(g)标志的存在与否,如果未找到匹配则为null

  1. var str = 'For more information, see Chapter 3.4.5.1';
  2. var re = /see (chapter \d+(\.\d)*)/i;
  3. var found = str.match(re);
  4. console.log(found);
  5. // logs [ 'see Chapter 3.4.5.1',
  6. // 'Chapter 3.4.5.1',
  7. // '.1',
  8. // index: 22,
  9. // input: 'For more information, see Chapter 3.4.5.1' ]
  10. // 'see Chapter 3.4.5.1' 是整个匹配。
  11. // 'Chapter 3.4.5.1' 被'(chapter \d+(\.\d)*)'捕获。
  12. // '.1' 是被'(\.\d)'捕获的最后一个值。
  13. // 'index' 属性(22) 是整个匹配从零开始的索引。
  14. // 'input' 属性是被解析的原始字符串。

返回调用字符串值的Unicode标准化形式。

String.prototype.normalize()返回调用字符串值的Unicode标准化形式。
normalize() 方法会按照指定的一种 Unicode 正规形式将当前字符串正规化。(如果该值不是字符串,则首先将其转换为一个字符串)。
语法:str.normalize([form])
参数:

  • form 可选
    • 四种 Unicode 正规形式(Unicode Normalization Form)"NFC""NFD""NFKC",或 "NFKD" 其中的一个, 默认值为 "NFC"

返回值:含有给定字符串的 Unicode 规范化形式的字符串。

  1. const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
  2. const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065';
  3. console.log(`${name1}, ${name2}`);
  4. // expected output: "Amélie, Amélie"
  5. console.log(name1 === name2);
  6. // expected output: false
  7. console.log(name1.length === name2.length);
  8. // expected output: false
  9. const name1NFC = name1.normalize('NFC');
  10. const name2NFC = name2.normalize('NFC');
  11. console.log(`${name1NFC}, ${name2NFC}`);
  12. // expected output: "Amélie, Amélie"
  13. console.log(name1NFC === name2NFC);
  14. // expected output: true
  15. console.log(name1NFC.length === name2NFC.length);
  16. // expected output: true

在当前字符串尾部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。

String.prototype.padEnd()在当前字符串尾部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。
padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

语法:str.padEnd(targetLength [, padString])
参数:

  • targetLength 当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
  • padString 可选。填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的缺省值为 “ “(U+0020)。

返回值:在原字符串末尾填充指定的填充字符串直到目标长度所形成的新字符串。

  1. const str1 = 'Breaded Mushrooms';
  2. console.log(str1.padEnd(25, '.'));
  3. // expected output: "Breaded Mushrooms........"
  4. const str2 = '200';
  5. console.log(str2.padEnd(5));
  6. // expected output: "200 "
  7. 'abc'.padEnd(10); // "abc "
  8. 'abc'.padEnd(10, "foo"); // "abcfoofoof"
  9. 'abc'.padEnd(6, "123456"); // "abc123"
  10. 'abc'.padEnd(1); // "abc"

在当前字符串头部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。

String.prototype.padStart()在当前字符串头部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。
padStart() 方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。

语法:str.padStart(targetLength [, padString])
参数:

  • targetLength 当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
  • padString 可选。填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的默认值为 “ “(U+0020)。

返回值:在原字符串开头填充指定的填充字符串直到目标长度所形成的新字符串。

  1. const str1 = '5';
  2. console.log(str1.padStart(2, '0'));
  3. // expected output: "05"
  4. const fullNumber = '2034399002125581';
  5. const last4Digits = fullNumber.slice(-4);
  6. const maskedNumber = last4Digits.padStart(fullNumber.length, '*');
  7. console.log(maskedNumber);
  8. // expected output: "************5581"
  9. 'abc'.padStart(10); // " abc"
  10. 'abc'.padStart(10, "foo"); // "foofoofabc"
  11. 'abc'.padStart(6,"123465"); // "123abc"
  12. 'abc'.padStart(8, "0"); // "00000abc"
  13. 'abc'.padStart(1); // "abc"

重复字符串

String.prototype.repeat()返回指定重复次数的由元素组成的字符串对象。
repeat() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。

语法:str.repeat(count)
参数:count 介于 0+Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。
返回值:包含指定字符串的指定数量副本的新字符串。
Exceptions:

  • RangeError: 重复次数不能为负数。
  • RangeError: 重复次数必须小于 infinity,且长度不会大于最长的字符串。 ```javascript “abc”.repeat(-1) // RangeError: repeat count must be positive and less than inifinity “abc”.repeat(0) // “” “abc”.repeat(1) // “abc” “abc”.repeat(2) // “abcabc” “abc”.repeat(3.5) // “abcabcabc” 参数count将会被自动转换成整数. “abc”.repeat(1/0) // RangeError: repeat count must be positive and less than inifinity

({toString : () => “abc”, repeat : String.prototype.repeat}).repeat(2)
//“abcabc”,repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.

  1. <a name="Kc7Sr"></a>
  2. ### 字符串替换
  3. [`String.prototype.replace()`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace)被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。<br />**`replace()`** 方法返回一个由替换值(`replacement`)替换部分或所有的模式(`pattern`)匹配项后的新字符串。模式可以是一个字符串或者一个[正则表达式](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/RegExp),替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果`pattern`是字符串,则仅替换第一个匹配项。
  4. 该方法并不改变调用它的字符串本身,而只是返回一个新的替换后的字符串。<br />在进行全局的搜索替换时,正则表达式需包含 `g` 标志。
  5. 语法:`str.replace(regexp|substr, newSubStr|function)`<br />参数:
  6. - `regexp `(pattern)
  7. - 一个[`RegExp`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/RegExp) 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。
  8. - `substr `(pattern)
  9. - 一个将被 `newSubStr` 替换的 [`字符串`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/String)。其被视为一整个字符串,而不是一个正则表达式。仅第一个匹配项会被替换。
  10. - `newSubStr` (replacement)
  11. - 用于替换掉第一个参数在原字符串中的匹配部分的[`字符串`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/String)。该字符串中可以内插一些特殊的变量名。参考下面的[使用字符串作为参数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace#%E4%BD%BF%E7%94%A8%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0)。
  12. - `function` (replacement)
  13. - 一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。参考下面的[指定一个函数作为参数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace#%E6%8C%87%E5%AE%9A%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0)。
  14. 返回值:一个部分或全部匹配由替代模式所取代的新的字符串。
  15. ```javascript
  16. const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
  17. const regex = /dog/gi;
  18. console.log(p.replace(regex, 'ferret'));
  19. // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
  20. console.log(p.replace('dog', 'monkey'));
  21. // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

使用字符串作为参数

替换字符串可以插入下面的特殊变量名:

变量名 代表的值
$$ 插入一个 “$”。
$& 插入匹配的子串。
`$`` 插入当前匹配的子串左边的内容。
$' 插入当前匹配的子串右边的内容。
$_n_ 假如第一个参数是 RegExp对象,并且 n 是个小于100的非负整数,那么插入第 n 个括号匹配的字符串。提示:索引是从1开始

指定一个函数作为参数

你可以指定一个函数作为第二个参数。在这种情况下,当匹配执行后,该函数就会执行。 函数的返回值作为替换字符串。 (注意:上面提到的特殊替换参数在这里不能被使用。) 另外要注意的是,如果第一个参数是正则表达式,并且其为全局匹配模式,那么这个方法将被多次调用,每次匹配都会被调用。
下面是该函数的参数:

变量名 代表的值
match 匹配的子串。(对应于上述的$&。)
p1,p2, ... 假如replace()方法的第一个参数是一个RegExp 对象,则代表第n个括号匹配的字符串。(对应于上述的$1,$2等。)例如,如果是用 /(\a+)(\b+)/ 这个来匹配,p1 就是匹配的 \a+p2 就是匹配的 \b+
offset 匹配到的子字符串在原字符串中的偏移量。(比如,如果原字符串是 'abcd',匹配到的子字符串是 'bc',那么这个参数将会是 1)
string 被匹配的原字符串。
NamedCaptureGroup 命名捕获组匹配的对象

(精确的参数个数依赖于 replace() 的第一个参数是否是一个正则表达式(RegExp)对象,以及这个正则表达式中指定了多少个括号子串,如果这个正则表达式里使用了命名捕获, 还会添加一个命名捕获的对象)
下面的例子将会使 newString 变成 'abc - 12345 - #$*%'

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

示例:

在 replace() 中使用正则表达式

在下面的例子中,replace() 中使用了正则表达式及忽略大小写标示。

  1. var str = 'Twas the night before Xmas...';
  2. var newstr = str.replace(/xmas/i, 'Christmas');
  3. console.log(newstr); // Twas the night before Christmas...

在 replace() 中使用 global 和 ignore 选项

下面的例子中,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用’oranges’替换掉了所有出现的”apples”.

  1. var re = /apples/gi;
  2. var str = "Apples are round, and apples are juicy.";
  3. var newstr = str.replace(re, "oranges");
  4. // oranges are round, and oranges are juicy.
  5. console.log(newstr);

交换字符串中的两个单词

下面的例子演示了如何交换一个字符串中两个单词的位置,这个脚本使用$1 和 $2 代替替换文本。

  1. var re = /(\w+)\s(\w+)/;
  2. var str = "John Smith";
  3. var newstr = str.replace(re, "$2, $1");
  4. // Smith, John
  5. console.log(newstr);


使用行内函数来修改匹配到的字符。

在这个例子中,所有出现的大写字母转换为小写,并且在匹配位置前加一个连字符。重要的是,在返回一个替换了的字符串前,在匹配元素前进行添加操作是必要的。
在返回前,替换函数允许匹配片段作为参数,并且将它和连字符进行连接作为新的片段。

  1. function styleHyphenFormat(propertyName) {
  2. function upperToHyphenLower(match) {
  3. return '-' + match.toLowerCase();
  4. }
  5. return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
  6. }

运行 styleHyphenFormat('borderTop')``,将返回 ‘border-top’。
因为我们想在最终的替换中进一步转变匹配结果,所以我们必须使用一个函数。这迫使我们在使用toLowerCase()方法前进行评估。如果我们尝试不用一个函数进行匹配,那么使用toLowerCase() 方法将不会有效。

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

这是因为 '$&'.toLowerCase() 会先被解析成字符串字面量(这会导致相同的’$&’)而不是当作一个模式。

将华氏温度转换为对等的摄氏温度

下面的例子演示如何将华氏温度转换为对等的摄氏温度。华氏温度用一个数字加一个”F”来表示,这个函数将返回一个数字加”C”来表示的摄氏温度。例如,如果输入是 212F,这个函数将返回 100C。如果输入的数字是 0F,这个方法将返回 “-17.77777777777778C”。
正则表达式test检查任何数字是否以 F 结尾。华氏温度通过第二个参数p1进入函数。这个函数基于华氏温度作为字符串传递给f2c函数设置成摄氏温度。然后f2c()返回摄氏温度。这个函数与Perl的 s///e 标志相似。

  1. function f2c(x)
  2. {
  3. function convert(str, p1, offset, s)
  4. {
  5. return ((p1-32) * 5/9) + "C";
  6. }
  7. var s = String(x);
  8. var test = /(\d+(?:\.\d*)?)F\b/g;
  9. return s.replace(test, convert);
  10. }

使用行内函数和正则来避免循环

下例把某种模式的字符串转换为一个对象数组(其元素为对象)。
输入:
一个由 x,- 和 _ 组成的字符串。

  1. x-x_
  2. ---x---x---x---
  3. -xxx-xx-x-
  4. _x_x___x___x___

输出:
一个数组对象。’x’ 产生一个 ‘on’ 状态,’-‘(连接符)产生一个 ‘off’ 状态,而 ‘_’ (下划线)表示 ‘on’ 状态的长度。

  1. [
  2. { on: true, length: 1 },
  3. { on: false, length: 1 },
  4. { on: true, length: 2 }
  5. ...
  6. ]

代码片段:

  1. var str = 'x-x_';
  2. var retArr = [];
  3. str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
  4. if (p1) { retArr.push({ on: true, length: p1.length }); }
  5. if (p2) { retArr.push({ on: false, length: 1 }); }
  6. });
  7. console.log(retArr);

该代码片段生成了一个数组,包含三个期望格式的对象,避免了使用 for 循环语句。

字符串搜索

String.prototype.search()对正则表达式和指定字符串进行匹配搜索,返回第一个出现的匹配项的下标。
search() 方法执行正则表达式和 String 对象之间的一个搜索匹配。
语法:str.search(regexp)
参数:regexp

返回值:如果匹配成功,则 search() 返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1

  1. const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
  2. // any character that is not a word character or whitespace
  3. const regex = /[^\w\s]/g;
  4. console.log(paragraph.search(regex));
  5. // expected output: 43
  6. console.log(paragraph[paragraph.search(regex)]);
  7. // expected output: "."
  8. var str = "hey JudE";
  9. var re = /[A-Z]/g;
  10. var re2 = /[.]/g;
  11. console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
  12. console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation

当你想要知道字符串中是否存在某个模式(pattern)时可使用 search(),类似于正则表达式的 test() 方法。当要了解更多匹配信息时,可使用 match()(但会更慢一些),该方法类似于正则表达式的 exec() 方法。

截取字符串

String.prototype.slice()摘取一个字符串区域,返回一个新的字符串,且不会改动原字符串。

语法:str.slice(beginIndex[, endIndex])
参数:

  • **beginIndex**
    • 从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 strLength + beginIndex 看待,这里的strLength 是字符串的长度(例如, 如果 beginIndex 是 -3 则看作是:strLength - 3
  • **endIndex**
    • 可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,slice() 会一直提取到字符串末尾。如果该参数为负数,则被看作是 strLength + endIndex,这里的 strLength 就是字符串的长度(例如,如果 endIndex 是 -3,则是, strLength - 3)。

返回值:返回一个从原字符串中提取出来的新字符串

  1. const str = 'The quick brown fox jumps over the lazy dog.';
  2. console.log(str.slice(31));
  3. // expected output: "the lazy dog."
  4. console.log(str.slice(4, 19));
  5. // expected output: "quick brown fox"
  6. console.log(str.slice(-4));
  7. // expected output: "dog."
  8. console.log(str.slice(-9, -5));
  9. // expected output: "lazy"

slice() 从一个字符串中提取字符串并返回新字符串。在一个字符串中的改变不会影响另一个字符串。也就是说,slice 不会修改原字符串(只会返回一个包含了原字符串中部分字符的新字符串)。
slice() 提取的新字符串包括beginIndex但不包括 endIndex。下面有两个例子。
例 1:str.slice(1, 4) 提取第二个字符到第四个字符(被提取字符的索引值(index)依次为 1、2,和 3)。
例 2:str.slice(2, -1) 提取第三个字符到倒数第一个字符。

例子

使用 slice() 创建一个新的字符串
  1. var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
  2. str2 = str1.slice(1, 8),
  3. str3 = str1.slice(4, -2),
  4. str4 = str1.slice(12),
  5. str5 = str1.slice(30);
  6. console.log(str2); // 输出:he morn
  7. console.log(str3); // 输出:morning is upon u
  8. console.log(str4); // 输出:is upon us.
  9. console.log(str5); // 输出:""

给 slice() 传入负值索引
  1. var str = 'The morning is upon us.';
  2. str.slice(-3); // 返回 'us.'
  3. str.slice(-3, -1); // 返回 'us'
  4. str.slice(0, -1); // 返回 'The morning is upon us'

分离字符串

String.prototype.split()通过分离字符串成字串,将字符串对象分割成字符串数组。
**split() **方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
语法:str.split([separator[, limit]])
参数:

  • **separator**
    • 指定表示每个拆分应发生的点的字符串。separator 可以是一个字符串或正则表达式。 如果纯文本分隔符包含多个字符,则必须找到整个字符串来表示分割点。如果在str中省略或不出现分隔符,则返回的数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。
  • **limit**
    • 一个整数,限定返回的分割片段数量。当提供此参数时,split 方法会在指定分隔符的每次出现时分割该字符串,但在限制条目已放入数组时停止。如果在达到指定限制之前达到字符串的末尾,它可能仍然包含少于限制的条目。新数组中不返回剩下的文本。

返回值:返回源字符串以分隔符出现位置分隔而成的一个 Array

  1. const str = 'The quick brown fox jumps over the lazy dog.';
  2. const words = str.split(' ');
  3. console.log(words[3]);
  4. // expected output: "fox"
  5. const chars = str.split('');
  6. console.log(chars[8]);
  7. // expected output: "k"
  8. const strCopy = str.split();
  9. console.log(strCopy);
  10. // expected output: Array ["The quick brown fox jumps over the lazy dog."]

找到分隔符后,将其从字符串中删除,并将子字符串的数组返回。如果没有找到或者省略了分隔符,则该数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str转换为字符数组。如果分隔符出现在字符串的开始或结尾,或两者都分开,分别以空字符串开头,结尾或两者开始和结束。因此,如果字符串仅由一个分隔符实例组成,则该数组由两个空字符串组成。
如果分隔符是包含捕获括号的正则表达式,则每次分隔符匹配时,捕获括号的结果(包括任何未定义的结果)将被拼接到输出数组中。但是,并不是所有浏览器都支持此功能。

Note: 当字符串为空时,split()返回一个包含一个空字符串的数组,而不是一个空数组,如果字符串和分隔符都是空字符串,则返回一个空数组。

示例

使用 split()

下例定义了一个函数:根据指定的分隔符将一个字符串分割成一个字符串数组。分隔字符串后,该函数依次输出原始字符串信息,被使用的分隔符,返回数组元素的个数,以及返回数组中所有的元素。

  1. function splitString(stringToSplit, separator) {
  2. var arrayOfStrings = stringToSplit.split(separator);
  3. console.log('The original string is: "' + stringToSplit + '"');
  4. console.log('The separator is: "' + separator + '"');
  5. console.log("The array has " + arrayOfStrings.length + " elements: ");
  6. for (var i=0; i < arrayOfStrings.length; i++)
  7. console.log(arrayOfStrings[i] + " / ");
  8. }
  9. var tempestString = "Oh brave new world that has such people in it.";
  10. var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
  11. var space = " ";
  12. var comma = ",";
  13. splitString(tempestString, space);
  14. splitString(tempestString);
  15. splitString(monthString, comma);

上例输出下面结果:

  1. The original string is: "Oh brave new world that has such people in it."
  2. The separator is: " "
  3. The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /
  4. The original string is: "Oh brave new world that has such people in it."
  5. The separator is: "undefined"
  6. The array has 1 elements: Oh brave new world that has such people in it. /
  7. The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
  8. The separator is: ","
  9. The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /

移出字符串中的空格

下例中,split() 方法会查找“0 或多个空白符接着的分号,再接着 0 或多个空白符”模式的字符串,找到后,就将空白符从字符串中移除,nameListsplit 的返回数组。

  1. var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
  2. console.log(names);
  3. var re = /\s*(?:;|$)\s*/;
  4. var nameList = names.split(re);
  5. console.log(nameList);

上例输出两行,第一行输出原始字符串,第二行输出结果数组。

  1. Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
  2. [ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]

限制返回值中分割元素数量

下例中,split 查找字符串中的 0 或多个空格,并返回找到的前 3 个分割元素(splits)。

  1. var myString = "Hello World. How are you doing?";
  2. var splits = myString.split(" ", 3);
  3. console.log(splits);

上例输出:

  1. ["Hello", "World.", "How"]

靠正则来分割使结果中包含分隔块

如果 separator 包含捕获括号(capturing parentheses),则其匹配结果将会包含在返回的数组中。

  1. var myString = "Hello 1 word. Sentence number 2.";
  2. var splits = myString.split(/(\d)/);
  3. console.log(splits);

上例输出:

  1. [ "Hello ", "1", " word. Sentence number ", "2", "." ]

使用一个数组来作为分隔符
  1. const myString = 'this|is|a|Test';
  2. const splits = myString.split(['|']);
  3. console.log(splits); //["this", "is", "a", "Test"]
  4. const myString = 'ca,bc,a,bca,bca,bc';
  5. const splits = myString.split(['a','b']);
  6. // myString.split(['a','b']) is same as myString.split(String(['a','b']))
  7. console.log(splits); //["c", "c,", "c", "c", "c"]


用split()来颠倒字符串顺序

注意这并非一种很健壮的逆转字符串的方法:

  1. const str = 'asdfghjkl';
  2. const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
  3. // split() returns an array on which reverse() and join() can be applied

如果字符串包含图形素集群,即使使用Unicode感知的拆分(use for example esrever instead),也不能工作。

  1. const str = 'résumé';
  2. const strReverse = str.split(/(?:)/u).reverse().join('');
  3. // => "́emuśer"

Bonus: use ===) operator to test if the original string was palindrome.

字符串起始位置判断

String.prototype.startsWith()判断字符串的起始位置是否匹配其他字符串中的字符。
**startsWith()** 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 truefalse
这个方法能够让你确定一个字符串是否以另一个字符串开头。这个方法区分大小写。

语法:str.startsWith(searchString[, position])
参数:

  • searchString
    • 要搜索的子字符串。
  • position 可选
    • str 中搜索 searchString 的开始位置,默认值为 0。

返回值:如果在字符串的开头找到了给定的字符则返回true;否则返回false

  1. const str1 = 'Saturday night plans';
  2. console.log(str1.startsWith('Sat'));
  3. // expected output: true
  4. console.log(str1.startsWith('Sat', 3));
  5. // expected output: false

返回指定位置开始的字符串中的字符

String.prototype.substr()通过指定字符数返回在指定位置开始的字符串中的字符。
它并非JavaScript核心语言的一部分,未来将可能会被移除掉。如果可以的话,使用 [substring()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring) 替代它.

返回指定两个下标之间的字符

String.prototype.substring()返回在字符串中指定两个下标之间的字符。
substring()方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。
语法:str.substring(indexStart[, indexEnd])
参数:

  • indexStart
    • 需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。
  • indexEnd 可选。
    • 一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。

返回值:包含给定字符串的指定部分的新字符串。

描述

substring 提取从 indexStartindexEnd(不包括)之间的字符。特别地:

  • 如果 indexStart 等于 indexEndsubstring 返回一个空字符串。
  • 如果省略 indexEndsubstring 提取字符一直到字符串末尾。
  • 如果任一参数小于 0 或为 NaN,则被当作 0。
  • 如果任一参数大于 stringName.length,则被当作 stringName.length
  • 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。见下面的例子。

    示例

例子:使用 substring

下例使用 substring 输出字符串 “Mozilla“ 中的字符:

  1. var anyString = "Mozilla";
  2. // 输出 "Moz"
  3. console.log(anyString.substring(0,3));
  4. console.log(anyString.substring(3,0));
  5. console.log(anyString.substring(3,-3));
  6. console.log(anyString.substring(3,NaN));
  7. console.log(anyString.substring(-2,3));
  8. console.log(anyString.substring(NaN,3));
  9. // 输出 "lla"
  10. console.log(anyString.substring(4,7));
  11. console.log(anyString.substring(7,4));
  12. // 输出 ""
  13. console.log(anyString.substring(4,4));
  14. // 输出 "Mozill"
  15. console.log(anyString.substring(0,6));
  16. // 输出 "Mozilla"
  17. console.log(anyString.substring(0,7));
  18. console.log(anyString.substring(0,10));

运用 length 属性来使用 substring()

下面一个例子运用了 String.length 属性去获取指定字符串的倒数元素。显然这个办法更容易记住,因为你不再像上面那个例子那样去记住起始位置和最终位置。

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


例子:替换一个字符串的子字符串

下例替换了一个字符串中的子字符串。可以替换单个字符和子字符串。该例结尾调用的函数将 “Brave New World“ 变成了 “Brave New Web“。

  1. function replaceString(oldS, newS, fullS) {
  2. // Replaces oldS with newS in the string fullS
  3. for (var i = 0; i < fullS.length; i++) {
  4. if (fullS.substring(i, i + oldS.length) == oldS) {
  5. fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
  6. }
  7. }
  8. return fullS;
  9. }
  10. replaceString("World", "Web", "Brave New World");

需要注意的是,如果 oldSnewS 的子字符串将会导致死循环。例如,尝试把 “World” 替换成 “OtherWorld”。一个更好的方法如下:

  1. function replaceString(oldS, newS,fullS){
  2. return fullS.split(oldS).join(newS);
  3. }

上面的代码只是子字符串操作的一个例子。如果你需要替换子字符串,更多时候会用到 String.prototype.replace()

字符串转小写

String.prototype.toLocaleLowerCase()根据当前区域设置,将符串中的字符转换成小写。对于大多数语言来说,toLowerCase的返回值是一致的。
String.prototype.toLowerCase()将字符串转换成小写并返回。
语法:

  • str.toLocaleLowerCase()
  • str.toLocaleLowerCase(locale)
  • str.toLocaleLowerCase([locale, locale, ...])

参数:

  • locale 可选
    • 参数 locale 指明要转换成小写格式的特定语言区域。 如果以一个数组 Array形式给出多个locales, 最合适的地区将被选出来应用(参见best available locale)。默认的locale是主机环境的当前区域(locale)设置。

返回值:根据任何特定于语言环境的案例映射规则将被调用字串转换成小写格式的一个新字符串。

toLocaleLowerCase() 方法返回根据任意区域语言大小写映射集而转换成小写格式的字符串。toLocaleLowerCase() 并不会影响字符串原本的值。在大多数情况下,该方法和调用 toLowerCase()的结果相同,但是在某些区域环境中,比如土耳其语,它的大小写映射并不遵循在Unicode中的默认的大小写映射,因此会有一个不同的结果。

例子

使用toLocaleLowerCase()
  1. 'ALPHABET'.toLocaleLowerCase(); // 'alphabet'
  2. '\u0130'.toLocaleLowerCase('tr') === 'i'; // true
  3. '\u0130'.toLocaleLowerCase('en-US') === 'i'; // false
  4. let locales = ['tr', 'TR', 'tr-TR', 'tr-u-co-search', 'tr-x-turkish'];
  5. '\u0130'.toLocaleLowerCase(locales) === 'i'; // true

字符串转大写

String.prototype.toLocaleUpperCase()根据当前区域设置,将字符串中的字符转换成大写,对于大多数语言来说,toUpperCase的返回值是一致的。

  1. const city = 'istanbul';
  2. console.log(city.toLocaleUpperCase('en-US'));
  3. // expected output: "ISTANBUL"
  4. console.log(city.toLocaleUpperCase('TR'));
  5. // expected output: "İSTANBUL"

String.prototype.toUpperCase()将字符串转换成大写并返回。
toUpperCase() 方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)。
语法:str.toUpperCase()
参数:
返回值:一个新的字符串,表示转换为大写的调用字符串。

  1. const sentence = 'The quick brown fox jumps over the lazy dog.';
  2. console.log(sentence.toUpperCase());
  3. // expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

返回用字符串表示的特定对象

String.prototype.toString()返回用字符串表示的特定对象。重写 Object.prototype.toString 方法。
String 对象覆盖了Object 对象的 toString 方法;并没有继承 Object.toString()。对于 String 对象,toString 方法返回该对象的字符串形式,和 String.prototype.valueOf() 方法返回值一样。
语法:str.toString()
返回值:一个表示调用对象的字符串。

  1. var x = new String("Hello world");
  2. alert(x.toString()) // 输出 "Hello world"

去除字符串首尾空格

String.prototype.trim()从字符串的开始和结尾去除空格。参照部分 ECMAScript 5 标准。
trim() 方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)。
语法:str.trim()
返回值:一个代表调用字符串两端去掉空白的新字符串。

  1. const greeting = ' Hello world! ';
  2. console.log(greeting);
  3. // expected output: " Hello world! ";
  4. console.log(greeting.trim());
  5. // expected output: "Hello world!";
  6. var orig = ' foo ';
  7. console.log(orig.trim()); // 'foo'
  8. // 另一个 .trim() 例子,只从一边删除
  9. var orig = 'foo ';
  10. console.log(orig.trim()); // 'foo'

兼容

如果 trim() 不存在,可以在所有代码前执行下面代码

  1. if (!String.prototype.trim) {
  2. String.prototype.trim = function () {
  3. return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  4. };
  5. }

去除字符串左侧空格

String.prototype.trimStart()String.prototype.trimLeft() 从字符串的左侧去除空格。
trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。
trimStart() / trimLeft() 方法移除原字符串左端的连续空白符并返回一个新字符串,并不会直接修改原字符串本身。
语法:

  • str.trimStart();
  • str.trimLeft();

返回值:一个新字符串,表示从其开头(左端)除去空格的调用字符串。

  1. const greeting = ' Hello world! ';
  2. console.log(greeting);
  3. // expected output: " Hello world! ";
  4. console.log(greeting.trimStart());
  5. // expected output: "Hello world! ";
  6. var str = " foo ";
  7. console.log(str.length); // 8
  8. str = str.trimStart() // 等同于 str = str.trimLeft();
  9. console.log(str.length); // 5
  10. console.log(str); // "foo "

去除字符串右侧空格

String.prototype.trimEnd()String.prototype.trimRight() 从字符串的右侧去除空格。
**trimEnd()**方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。
trimEnd() / trimRight()方法移除原字符串右端的连续空白符并返回,trimEnd() / trimRight()方法并不会直接修改原字符串本身。
语法:

  • str.trimEnd();
  • str.trimRight();

返回值:一个新字符串,表示从调用字串的末(右)端除去空白。

  1. const greeting = ' Hello world! ';
  2. console.log(greeting);
  3. // expected output: " Hello world! ";
  4. console.log(greeting.trimEnd());
  5. // expected output: " Hello world!";
  6. var str = " foo ";
  7. alert(str.length); // 8
  8. str = str.trimRight(); // 或写成str = str.trimEnd();
  9. console.log(str.length); // 6
  10. console.log(str); // ' foo'

String.prototype.valueOf()返回特定对象的原始值。重写 Object.prototype.valueOf 方法。
valueOf() 方法返回 String 对象的原始值;
此方法通常由JavaScript在内部调用,而不是在代码中显式调用。

语法:str.valueOf()
参数:
返回值:

  1. const stringObj = new String('foo');
  2. console.log(stringObj);
  3. // expected output: String { "foo" }
  4. console.log(stringObj.valueOf());
  5. // expected output: "foo"
  6. var x = new String('Hello world');
  7. console.log(x.valueOf()); // Displays 'Hello world'

返回一个新的迭代器对象

String.prototype[@@iterator]()返回一个新的迭代器对象,该对象遍历字符串值的索引位置,将每个索引值作为字符串值返回。
[@@iterator]() 方法返回一个新的Iterator对象,它遍历字符串的代码点,返回每一个代码点的字符串值。
语法:string[Symbol.iterator]
返回值:一个新的Iterator对象。

  1. const str = 'The quick red fox jumped over the lazy dog\'s back.';
  2. const iterator = str[Symbol.iterator]();
  3. let theChar = iterator.next();
  4. while (!theChar.done && theChar.value !== ' ') {
  5. console.log(theChar.value);
  6. theChar = iterator.next();
  7. // expected output: "T"
  8. // "h"
  9. // "e"
  10. }

示例

使用@@iterator
  1. var string = 'A\uD835\uDC68';
  2. var strIter = string[Symbol.iterator]();
  3. console.log(strIter.next().value); // "A"
  4. console.log(strIter.next().value); // "\uD835\uDC68"

通过 for..of 使用@@iterator
  1. var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';
  2. for (var v of string) {
  3. console.log(v);
  4. }
  5. // "A"
  6. // "\uD835\uDC68"
  7. // "B"
  8. // "\uD835\uDC69"
  9. // "C"
  10. // "\uD835\uDC6A"

算法练习

实现 strStr()

https://leetcode-cn.com/problems/implement-strstr/

有效的括号

https://leetcode-cn.com/problems/valid-parentheses/

罗马数字转整数

https://leetcode-cn.com/problems/roman-to-integer/

验证回文串

https://leetcode-cn.com/problems/valid-palindrome/

最后一个单词的长度

https://leetcode-cn.com/problems/length-of-last-word/

反转字符串

https://leetcode-cn.com/problems/reverse-string/