字符串的方法和属性

147 阅读5分钟

不改变原始字符串:concat()、slice()、substr()、substring()

转换为字符串

toString():唯一的用途就是返回当前值的字符串的等价物

let age = 11;
let ageAsString = age.toString();    //  字符串“11”
let found = true;
let foundAsString = found.toString();// 字符串“true”

String():始终会返回表示相应类型值的字符串

String()函数遵循如下规则:

  • 如果值有toString()方法,则调用该方法并返回结果。
  • 如果值是null,则返回"null"。
  • 如果值是undefined,则返回"undefinde"。
let value1 = 10;
let value2 = true;
let value3 = null;
let value4 = undefined;
console.log(String(value1));      // "10"
console.log(String(value2));      // "true"
console.log(String(value3));      // "null"
console.log(String(value4));      // "undefined"

字符串属性

length:每个String对象都有一个length属性,表示字符串中字符的数量。

let stringValue = "hello world";
console.log(stringValue.length)    // 11

字符串方法

charAt():方法返回给定索引位置的字符串,由传给方法的整数参数指定。

let message = 'abcde';
console.log(message.charAt(2));    // "c"

concat():用于将一个或多个字符串拼接成一个新的字符串(不改变原字符串)

但更常用的方式使用加号操作符(+)

let stringValue = "hello ";
let result = stringValue.concat("world");
console.log(result);          // "hello world"
console.log(stringValue);     // "hello "

//可接受任意多个参数,因此可一次性拼接多个字符串。
let stringValue = "hello ";
let result = stringValue.concat("world", "!");
console.log(result);          // "hello world!"
console.log(stringValue);     // "hello "

截取字符串方法

slice()、substr()和substring()。这3个方法都返回调用它们的字符串的一个子字符串,而且都接受一个或两个参数。且都不会改变原始字符串。

slice() and substring():接受第一次参数表示子字符串开始的位置,第二个字符串结束的位置(在这两个之间都会被提取)

substr():接受的第一个参数表示子字符串开始的位置,第二个参数返回字符串的数量。

let stringValue = "hello world";
console.log(stringValue.slice(3));         // "lo world"
console.log(stringValue.substring(3));     // "lo world"
console.log(stringValue.substr(3));        // "lo world"
console.log(stringValue.slice(3,7));       // "lo w"
console.log(stringValue.substring(3,7));   // "lo w"
console.log(stringValue.substr(3,7));      // "lo worl" //位置

//带负数的时候还是不一样的
let stringValue = "hello world";
console.log(stringValue.slice(-3));         // "rld"
console.log(stringValue.substring(-3));     // "hello world"
console.log(stringValue.substr(-3));        // "rld"
console.log(stringValue.slice(3,-4));       // "lo w"
console.log(stringValue.substring(3,-4));   // "hel"
console.log(stringValue.substr(3,-4));      // ""empty string)

slice():负数的时候倒着数,从-1开始

substring():不存在负数,将负数转化为0

substr():第一个参数(负数的时候倒着数,从-1开始),第二个负参数将数值转化为0

字符串位置方法

indexOf():从字符串开头开始搜索传入的子字符串,并返回位置(如果没找到,则返回-1)

lastIndexOf():从字符串末尾开始搜索传入的子字符串,并返回位置(如果没找到,则返回-1)

let stringValue = "hello world";
console.log(stringValue.indexOf("o"));         // 4
console.log(stringValue.lastIndexOf("o"));     // 7
//两个参数
let stringValue = "hello world";
console.log(stringValue.indexOf("o",6));         // 7
console.log(stringValue.lastIndexOf("o",6));     // 4

第二个参数:(表示开始搜索的位置)

indexOf():从这个参数指定的位置开始搜索到最后,(忽略该位置之前的字符)

lastIndexOf():从这个参数指定的位置向字符串开头(向前)搜索,(忽略该位置之后的字符(直到字符串末尾的字符))

字符串包含方法

startsWith()、endsWith()、includes()返回布尔值

startsWith():检查开始于索引0的匹配项。(开头是否包含这个字符串)

endsWith():检查开始于索引(string.length-subString.length)的匹配项

(结尾是否包含这个字符串)

includes():检查整个字符串,是否包含这个字符串

let message = "foobarbaz";
console.log(message.startsWith("foo"));     // true
console.log(message.startsWith("bar"));     // false

console.log(message.endsWith("baz"));       // true
console.log(message.endsWith("bar"));       // false

console.log(message.includes("bar"));       // true
console.log(message.includes("qux"));       // false

第二个参数:

startsWith() and includes()表示开始搜索的位置

(如果传入第二个参数,则意味着这俩个方法会从指定的位置向着字符串末尾搜索,忽略该位置之前的所有字符。)

endsWith()表示应该当作字符串末尾的位置

(如果不提供这个参数,默认就是字符串的长度。如果提供这个参数,就好像字符串只有这么多字符一样。)

let message = "foobarbaz";
console.log(message.startsWith("foo"));     // true
console.log(message.startsWith("foo",1));   // false

console.log(message.includes("bar"));       // true
console.log(message.includes("bar",4));     // false

console.log(message.endsWith("bar"));         // false
console.log(message.endsWith("bar",6));       // true
//代表截取长度为6的字符串,然后末尾包括bar

trim():删除前后所有的空格符,再返回结果。(原字符串不受影响)

重复字符串

repeat():(重复)接受一个整数参数,表示将字符串复制多少次,然后 返回拼接所有副本后的结果。

let stringValue = "      hello world       ";
let trimmedStringValue = stringValue.trim();
console.log(stringValue);          // "      hello world"
console.log(trimmedStringValue);   // "hello world"

//repeat()
let stringvalue = "na   ";
console.log(stringvalue.repeat(3) + "batman");   
// "na   na   na   batman"

padStart() and padEnd():复制字符串

如果小于指定的长度,则在相应一边填充字符串直到满足长度条件

第一个参数是长度,第二个参数是可选的填充字符串,默认为空格

let stringValue = "foo";
console.log(stringValue.padStart(6));        // "   foo"
console.log(stringValue.padStart(9,"."));    // "......foo"
console.log(stringValue.padEnd(6));          // "foo   "
console.log(stringValue.padEnd(9,"."));      // "foo......"

//两个参数
console.log(stringValue.padStart(8,"bar"));    // "barbafoo"
console.log(stringValue.padStart(2));          // "foo"
console.log(stringValue.padEnd(8,"bar"));      // "foobarba"
console.log(stringValue.padEnd(2));            // "foo"

字符串迭代与结构

字符串原型上暴露了一个@@iterator方法,表示可以迭代字符串的每个字符。可以向下面这样手动使用迭代器:

let message = "abc";
let stringIterator = message[Symbol.iterator]();
console.log(stringIterator.next());      // {value: 'a', done: false}
console.log(stringIterator.next());       // {value: 'b', done: false}
console.log(stringIterator.next());       // {value: 'c', done: false}
console.log(stringIterator.next());    // {value: undefined, done: true}

for-of:循环中可以通过这个迭代器按序访问每个字符

通过解构操作符来解构:

for (const c of "abcde") {
    console.log(c)
} 
// "a"
// "b"
// "c"
// "d"
// "e"

let message = "abcde";
console.log([...message]);    // ['a', 'b', 'c', 'd', 'e']

字符串大小写转换

toLowerCase() :变成全小写

toLocaleLowerCase():变成全小写

toUpperCase() :变成全部大写

toLocaleUpperCase():变成全部大写

let stringValue = "hello world";
console.log(stringValue.toLocaleUpperCase());    // "HELLO WORLD"
console.log(stringValue.toUpperCase());          // "HELLO WORLD"
console.log(stringValue.toLocaleLowerCase());    // "hello world"
console.log(stringValue.toLowerCase());          // "hello world"

字符串模式匹配方法

**match():**这个方法接受一个参数,可以是一个正则表达式字符串,也可以是一个RegExp对象。

let text = "cat,bat,sat,fat";
let pattern = /.at/;
let matches = text.match(pattern);// 等价于pattern.exec(text)
console.log(matches[0]);               // "cat"
console.log(pattern.lastIndex);        // 0

search():接受一个参数,(可以是正则表达式字符串,也可以是RegExp对象),返回模式第一个匹配的位置索引,如果没有找到则返回-1(始终从字符串的开头向后匹配)

let text = "cat,bat,sat,fat";
let pos = text.search(/at/);
console.log(pos);                  // 1

split(): 将字符串拆分成数组,(第二个参数表示数组的大小)