JavaScript之String方法属性

本文最后更新于 2025年7月30日 下午

参考:

  1. https://juejin.cn/post/6844903927754784781
  2. https://juejin.cn/post/6921593483757092878
  3. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String

字符串方法

1
2
3
String.raw();
String.fromCharcode();
String.fromCodePoint();

String.raw()

String.raw() 方法用来获取一个模板字符串的原始字符串。

接收参数:

  • callSite。一个模板字符串的“调用点对象”。类似 { raw: ['foo', 'bar', 'baz'] }
  • substitutions。任意个可选的参数,表示任意个内插表达式对应的值。
  • templateString。模板字符串,可包含占位符${...}
1
2
3
4
5
String.raw`Hi\n${2 + 3}!`; // 'Hi\\n5!' // Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
const name = "Bob";
String.raw`Hi\n${name}!`; // 'Hi\\nBob!'
String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
String.raw({ raw: ["foo", "bar", "baz"] }, 2 + 3, "Java" + "Script"); // 'foo5barJavaScriptbaz'

String.fromCharcode()

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

接收参数:

  • num1, …, numN。一系列 UTF-16 代码单元的数字。范围介于 0 到 65535(0xFFFF)之间。大于 0xFFFF 的数字将被截断。不进行有效性检查。
1
String.fromCharCode(189, 43, 190, 61); // '½+¾='

String.fromCodePoint()

String.fromCodePoint() 方法返回使用指定的代码点序列创建的字符串。

接收参数:

  • num1, …, numN。一串 Unicode 编码位置,即“代码点”。
1
String.fromCodePoint(9731, 9733, 9842, 0x2f804); // '☃★♲你'

字符串实例属性

1
String.prototype.length;

length 字符串长度

length 属性表示字符串的长度,不可以设置该属性来改变字符串的长度。

1
2
3
4
5
6
7
const x = "Mozilla";
const empty = "";

console.log("Mozilla is " + x.length + " code units long");
// "Mozilla is 7 code units long"
console.log("The empty string is has a length of " + empty.length);
// "The empty string is has a length of 0"

字符串实例方法

字符串实例方法都不会改变原字符串。

增删改替

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String.prototype.repeat();
String.prototype.split();
String.prototype.slice();
String.prototype.substring();
String.prototype.concat();
String.prototype.replace();
String.prototype.replaceAll();
String.prototype.padEnd();
String.prototype.padStart();
String.prototype.trim();
String.prototype.trimEnd();
String.prototype.trimRight();
String.prototype.trimStart();
String.prototype.trimLeft();

repeat() 重复

repeat() 方法构造并返回一个新字符串,新字符串包含被连接在一起的指定数量的字符串的副本。

接收一个参数:

  • count(可选):表示在新构造的字符串中重复多少遍原字符串,默认为 0。
1
2
3
const str = "abcdef";
str.repeat(); // ''
str.repeat(3); // 'abcdefabcdefabcdef'

split() 分割

split() 方法使用指定的分隔符字符串,将调用该方法的字符串分割成子字符串数组并返回。

接收两个参数:

  • separator(可选):指定表示每个拆分应发生的点的字符串。可以是一个字符串或正则表达式。若省略或者不出现分隔符,则返回的数组包含一个由整个字符串组成的元素;若为空字符串,则将原字符串中每个字符的数组形式返回。
  • limit(可选):限定返回的分割片段数量。默认不限定。
1
2
3
4
const str = "a,b,c,de,f";
str.split(""); // ['a', ',', 'b', ',', 'c', ',', 'd', 'e', ',', 'f']
str.split(","); // ['a', 'b', 'c', 'de', 'f']
str.split(); // ['a,b,c,de,f']

slice() 提取

slice() 方法提取调用该方法的字符串的一部分并返回。

接收两个参数:

  • beginIndex(必需):从该索引处开始提取原字符串中的字符。接受负值。
  • endIndex(可选):在该索引处前结束提取字符串。默认提取完字符串。接受负值。
1
2
3
const str = "aaabbbccc";
str.slice(0); // 'aaabbbccc'
str.slice(0, 3); // 'aaa'

substring() 截取

substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集。

接收两个参数:

  • indexStart(必需):从该索引处开始截取原字符串中的字符。接受负值。
  • indexEnd(可选):在该索引处前结束截取字符串。默认截取完字符串。接受负值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const anyString = "Mozilla";

// 输出 "Moz"
anyString.substring(0, 3));
anyString.substring(3, 0));
anyString.substring(3, -3));
anyString.substring(3, NaN));
anyString.substring(-2, 3));
anyString.substring(NaN, 3));

// 输出 "lla"
anyString.substring(4, 7));
anyString.substring(7, 4));

// 输出 ""
anyString.substring(4, 4));

// 输出 "Mozill"
anyString.substring(0, 6));

// 输出 "Mozilla"
anyString.substring(0, 7));
anyString.substring(0, 10));

concat() 合并

concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。

接收参数:

  • 要合并的字符串。可以是任意多个。
1
2
3
const str = "aaa";
str.concat("bbb"); // 'aaabbb'
str.concat("bbb", "ccc"); // 'aaabbbccc'

replace() 替换首个

replace() 方法返回一个由替换值替换第一个模式匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。

接收参数:

  • regexp | substr:regexp 指一个 RegExp 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。substr 指一个将被 newSubStr 替换的字符串。其被视为一整个字符串,而不是一个正则表达式。
  • newSubStr | function:newSubStr 指用于替换掉第一个参数在原字符串中的匹配部分的字符串。该字符串中可以内插一些特殊的变量名。function 指一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。
1
2
3
4
const str = "aaa";
const string = "Twas the night before Xmas...";
str.replace("a", "bbb"); // 'bbbaa'
string.replace(/xmas/i, "Christmas"); // 'Twas the night before Christmas...'

replaceAll() 替换所有

replaceAll() 方法返回一个由替换值替换所有模式匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。

接收参数:

  • regexp | substr:regexp 指一个 RegExp 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。substr 指一个将被 newSubStr 替换的字符串。其被视为一整个字符串,而不是一个正则表达式。
  • newSubStr | function:newSubStr 指用于替换掉第一个参数在原字符串中的匹配部分的字符串。该字符串中可以内插一些特殊的变量名。function 指一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。
1
2
3
4
5
const str = "aaa";
const p = "The fox jumps over the dog. If the dog reacted, was it really lazy?";
const regex = /Dog/gi;
str.replaceAll("a", "bbb"); // 'bbbbbbbbb'
p.replaceAll(regex, "ferret"); // 'The fox jumps over the ferret. If the ferret reacted, was it really lazy?'

padEnd() 结尾填充

padEnd() 方法用一个字符串从当前字符串的末尾(右侧)开始填充当前字符串,返回填充后字符串。

接收两个参数:

  • targetLength(必需):需填充到的目标长度。若其小于当前字符串的长度,则返回当前字符串本身。
  • padString (可选):用于填充的字符串。默认为空格。
1
2
3
4
const str = "aaa";
str.padEnd(5); // 'aaa '
str.padEnd(5, "s"); // 'aaass'
str.padEnd(5, "sssss"); // 'aaass'

padStart() 开头填充

padStart() 方法用一个字符串从当前字符串的开头(左侧)开始填充当前字符串,返回填充后字符串。

接收两个参数:

  • targetLength(必需):需填充到的目标长度。若其小于当前字符串的长度,则返回当前字符串本身。
  • padString (可选):用于填充的字符串。默认为空格。
1
2
3
4
const str = "aaa";
str.padStart(5); // ' aaa'
str.padStart(5, "s"); // 'ssaaa'
str.padStart(5, "sssss"); // 'ssaaa'

trim() 删除空格

trim() 方法会将调用该方法的字符串的两端删除空白字符。

trimEnd() 删除结尾空格

trimEnd() 方法会将调用该方法的字符串的结尾删除空白字符。trimRight() 是此方法的别名。

trimStart() 删除开头空格

trimStart() 方法会将调用该方法的字符串的开头删除空白字符。trimLeft() 是此方法的别名。

查找返回

1
2
3
4
5
6
7
8
9
10
11
12
String.prototype.at();
String.prototype.charAt();
String.prototype.indexOf();
String.prototype.lastIndexOf();
String.prototype.includes();
String.prototype.startsWith();
String.prototype.endsWith();
String.prototype.match();
String.prototype.matchAll();
String.prototype.search();
String.prototype.charCodeAt();
String.prototype.codePointAt();

at() 由位置找元素

at() 方法用于在字符串中查找给定位置对应的字符,返回该位置处的字符,找不到则返回 undefined。

接收一个参数:

  • index(可选)。要查找的字符的位置。接受负值,默认值为 0。
    (方括号语法只能是正整数且必须给参数)
1
2
3
4
const str = "abcdefg";
str.at(5); // 'f'
str.at(-3); // 'e'
str.charAt(10); // undefined

charAt() 由位置找元素

charAt() 方法用于在字符串中查找给定的一个位置,返回该位置处的字符,找不到则返回空字符串。

接收一个参数:

  • index(可选):要查找的字符的位置。不接受负值,默认值为 0。
    (方括号语法只能是正整数且必须给参数)
1
2
3
4
const str = "abcdefg";
str.charAt(5); // 'f'
str.charAt(-3); // ''
str.charAt(10); // ''

indexOf() 由元素找位置

indexOf() 方法用于在字符串中查找给定字符串对应的位置,从 fromIndex 位置开始,从前向后搜索,只返回首个满足条件的位置,如果不存在则返回 -1。使用严格相等搜索元素。

接收两个参数:

  • searchValue(必需):指定要查找的字符串。
  • fromIndex(可选):起始搜索位置。接受负值,默认值为 0。
1
2
3
const str = "abcdefg";
str.indexOf("a"); // 0
str.indexOf("fg"); // 5

lastIndexOf() 由元素找位置

lastIndexOf() 方法用于在字符串中查找给定字符串对应的位置,从 fromIndex 位置开始,从后向前搜索,只返回首个满足条件的位置,如果不存在则返回 -1。使用严格相等搜索元素。

接收两个参数:

  • searchValue(必需):指定要查找的字符串。
  • fromIndex(可选):起始搜索位置。接受负值,默认值为 0。
1
2
3
const str = "abcdefg";
str.lastIndexOf("a"); // 0
str.lastIndexOf("fg"); // 5

includes() 是否包含元素

includes() 方法用于在字符串中查找给定字符串,从 fromIndex 位置开始,从后向前搜索,返回布尔值,表示是否至少找到一个与指定字符串匹配的项。使用严格相等搜索元素。

接收两个参数:

  • searchString(必需):要搜索的指定的字符串。
  • fromIndex(可选):起始搜索位置。接受负值,默认值为 0。
1
2
3
const str = "abcdefg";
str.includes("a"); // true
str.includes("i"); // false

startsWith() 查找是否开头

startsWith() 方法用于判断调用该方法的字符串是否以给定的字符串开头,返回布尔值。

接收两个参数:

  • searchString(必需):要搜索的字符串。
  • position(可选):起始搜索位置。接受负值,默认值为 0。
1
2
3
const str = "abcdefg";
str.startsWith("a"); // true
str.startsWith("i"); // false

endsWith() 查找是否结尾

endsWith() 方法用于判断调用该方法的字符串是否以给定的字符串结尾,返回布尔值。

接收两个参数:

  • searchString(必需):要搜索的字符串。
  • position(可选):起始搜索位置。接受负值,默认值为 0。
1
2
3
const str = "abcdefg";
str.includes("fg"); // true
str.lastIndexOf("i"); // false

match()

match() 方法检索返回一个字符串匹配正则表达式的结果。

接收参数:

  • regexp。一个正则表达式对象。如果传入一个非正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。如果没有给出任何参数并直接使用 match() 方法,将会得到一 个包含空字符串的 [“”] 。
1
2
3
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
const regex = /[A-Z]/g;
paragraph.match(regex); // ["T", "I"]

matchAll()

matchAll() 方法检索返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。

接收参数:

  • regexp。一个正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp。RegExp 必须是设置了全局模式 g 的形式,否则会抛出异常 TypeError。
1
2
3
4
5
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
const array = [...str.matchAll(regexp)];
array[0]; // ["test1", "e", "st1", "1"]
array[1]; // ["test2", "e", "st2", "2"]

search() 方法执行正则表达式和调用该方法的字符串之间的一个搜索匹配。

接收参数:

  • regexp。一个正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp。
1
2
3
4
5
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
const regex = /[^\w\s]/g;
paragraph.search(regex); // 43
paragraph[paragraph.search(regex)]; // "."

charCodeAt() 查找返回 UTF-16 代码

charCodeAt() 方法从调用该方法的字符串中返回指定位置的字符的 UTF-16 代码单元。

接收一个参数:

  • index(可选):要查找的字符的位置。介于 0 到字符串长度减 1 之间,默认为 0。
1
2
3
4
5
6
7
8
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(
`The character code ${sentence.charCodeAt(
index
)} is equal to ${sentence.charAt(index)}`
);
// "The character code 113 is equal to q"

codePointAt() 查找返回 Unicode 编码

codePointAt() 方法从调用该方法的字符串中返回指定位置的字符的 Unicode 编码点值的非负整数。

接收一个参数:

  • pos(可选):要查找的字符的位置。介于 0 到字符串长度减 1 之间,默认为 0。
1
2
3
"ABC".codePointAt(1); // 66
"\uD800\uDC00".codePointAt(0); // 65536
"XYZ".codePointAt(42); // undefined

其它

1
2
3
4
5
6
7
8
String.prototype.toLowerCase();
String.prototype.toUpperCase();
String.prototype.toLocaleLowerCase();
String.prototype.toLocaleUpperCase();
String.prototype.localeCompare();
String.prototype.normalize();
String.prototype.valueOf();
String.prototype.toString();

toLowerCase() 转小写

toLowerCase() 方法会将调用该方法的字符串的每个字母都转为小写形式并返回。
(如果调用该方法的值不是字符串类型会被强制转换)

toUpperCase() 转大写

toUpperCase() 方法会将调用该方法的字符串的每个字母都转为大写形式并返回。
(如果调用该方法的值不是字符串类型会被强制转换)

toLocaleLowerCase() 转本地小写

toLocaleLowerCase() 方法根据本地主机语言环境把字符串转换为小写格式并返回。

toLocaleUpperCase() 转本地大写

toLocaleUpperCase() 方法根据本地主机语言环境把字符串转换为大写格式并返回。

localeCompare()

localeCompare() 方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。

normalize()

normalize() 方法会按照指定的一种 Unicode 正规形式将当前字符串正规化。

valueOf()

valueOf() 方法返回指定对象的原始值。

toString()

toString() 方法返回指定对象的字符串形式。


JavaScript之String方法属性
https://xuekeven.github.io/2021/09/08/JavaScript之String方法属性/
作者
Keven
发布于
2021年9月8日
更新于
2025年7月30日
许可协议