String方法总结

108 阅读5分钟

String.prototype

  • big() 用大号字体显示字符串。
  • blink() 显示闪动字符串。
  • bold() 使用粗体显示字符串。
  • sup() 把字符串显示为上标。
  • sub() 把字符串显示为下标。
  • strike() 使用删除线来显示字符串。
  • small() 使用小字号来显示字符串。
  • toLocaleLowerCase() 把字符串转换为小写。
  • toLocaleUpperCase() 把字符串转换为大写。
  • toLowerCase() 把字符串转换为小写。
  • toUpperCase() 把字符串转换为大写。
  • toSource() 代表对象的源代码。
  • toString() 返回字符串。
  • valueOf() 返回某个字符串对象的原始值。
  • trim(),trimLeft(),trimRight() 去除首尾空格

concat

hello.concat('Kevin', '. Have a nice day.') // Hello, Kevin. Have a nice day.

charAt() 返回在指定位置的字符。

var anyString = "Brave new world"; anyString.charAt(0) // B

charCodeAt() 返回在指定的位置的字符的 Unicode 编码。

"ABC".charCodeAt(0) // 65

indexOf

与数组方法类似。

stringObject.indexOf(searchvalue,fromindex)

fromindex规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

lastIndexOf

与indexOf相反。

indexOf和lastIndexOf方法对大小写敏感!

localeCompare

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

  • 当 引用字符串 在 比较字符串 前面时返回 -1
  • 当 引用字符串 在 比较字符串 后面时返回 1
  • 相同位置时返回 0 'a'.localeCompare('a'); // 0 'a'.localeCompare('c'); // -1 'check'.localeCompare('against') // 1

截取字符串

slice(start, end)

start,要抽取的片断的起始下标,如果为负,则从尾部算起。 end,要抽取的片段的结尾的下标,如果为负,则从尾部算起。

String.slice() 与 Array.slice() 相似

substring(start, stop)

start必需。要抽取的片断的起始下标,不能为负。 stop可选。比要提取的子串的最后一个字符的位置多1,不能为负。

如果参数 start 与 stop 相等,那返回一个空串。 如果 start 比 stop 大,那在提取子串之前会先交换这两个参数。 如果同时为负,则返回空串。 如果一个值为负,则转为0,而且如果start 比 stop 大,会交换值。

substr(start, length) --不推荐

start,要抽取的片断的起始下标,如果为负,则从尾部算起。 length,如果为负,则转为0。

includes(), startsWith(), endsWith()

  • includes(searchValue, start):返回布尔值,表示是否找到了参数字符串。
  • startsWith(searchValue, start):返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith(searchValue, start):返回布尔值,表示参数字符串是否在原字符串的尾部。
let s = 'Hello world!';

s.startsWith('world', 6);    // true
s.endsWith('Hello', 5);      // true
s.includes('Hello', 6);      // false
s.includes('o');             // true

repeat(value)

返回一个新字符串,表示将原字符串重复n次。

  • 如果value数是负数或者Infinity,会报错。但是,如果参数是 0 到-1 之间的小数,则等同于 0。
  • 如果value是字符串,则会先转换成数字。
  • value为NaN等同于 0。
  • value如果是小数,会被取整。
'a'.repeat(3);     // "aaa"
'a'.repeat(-1);    //VM449:1 Uncaught RangeError: Invalid count value
'a'.repeat('3n');  //""
'a'.repeat('3');   //"aaa"
'a'.repeat(NaN);   //""
'a'.repeat(1.6);   //"a"

padStart(),padEnd()

  • padStart(length, string)用于头部补全。
  • padEnd(length, string)用于尾部补全。
'aaa'.padStart(2, 'ab');            //"aaa"
'aaa'.padStart(10, '0123456789');   //"0123456aaa"
'aaa'.padStart(10)                  //"       aaa"
'aaa'.padEnd(6, 'cd')               //"aaacdc"

正则相关

split

把一个字符串分割成字符串数组。

stringObject.split(separator, howmany)     //separator必需,字符串或正则表达式
var str="How are you doing today?";
str.split(/\s+/);      //"How", "are", "you", "doing", "today?"

如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。 String.split() 执行的操作与 Array.join 执行的操作是相反的。 ###match 可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

stringObject.match(searchvalue | reg)

字符串检索

var str="Hello world!";
str.match('w');      //["w", index: 6, input: "Hello world!", groups: undefined]

正则检索

// 全局匹配
var str="1 plus 2 equal 3";
str.match(/\d+/g);      //["1", "2", "3"]

var str="1 plus 2 equal 3";
str.match(/\d+/);      //["1", index: 0, input: "1 plus 2 equal 3", groups: undefined]

replace

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

stringObject.replace(reg | substr, replacement)

字符串替换

'aaaccc'.replace('ccc', 'b');    //'aaab'

'aaaccc'.replace('bbb', 'b');    //'aaaccc'

'aaaccc'.replace('a', 'b');     //"baaccc"

正则替换

'aaaccc'.replace(/\w/, 'b')     //"baaccc"

//全局匹配
'aaaccc'.replace(/\w/g, 'b')    //"bbbbbb"

replacement 可以是字符串,也可以是函数。但是 replacement 中的 $ 字符具有特定的含义。

字符 替换文本
字符 替换文本
$1、$2、...、$99 与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。
$& 与 regexp 相匹配的子串。
$` 位于匹配子串左侧的文本。
$' 位于匹配子串右侧的文本。
$$ 直接量符号。
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$1'); // "aa"
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$4'); // "$4"
    
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$&'); //"aa123BB"
'aa123BB'.replace(/(\d+)/g, '$`'); //"aaaaBB"
'aa123BB'.replace(/(\d+)/g, "$'"); //"aaBBBB"
'aa123BB'.replace(/(\d+)/g, '$$'); //"aa$BB"

replace() 方法的参数 replacement 可以是函数而不是字符串。在这种情况下,每个匹配都调用该函数,它返回的字符串将作为替换文本使用。

'aaaccc'.replace(/\w/g, function() {
    return 'b';
});
//"bbbbbb"

'aaaccc'.replace(/\w/, function() {
    return 'b';
});
//"baaccc"

replaceAll

必须使用全局 RegExp 调用 replaceAll

'aabbcc'.replaceAll('b', '.')  // 'aa..cc'
'aabbcc'.replaceAll(/b/g, '.') // "aa..cc"

search

stringObject.search(searchvalue | reg)
'aaaccc'.search('ccc');    //3
'aaaccc'.search(/ccc/);    //3  
var str="Visit W3School!";
str.search(/W3School/);    //6

search() 对大小写敏感

match

var reg = new RegExp("a(bc)")
var str = "3abc4,5abc6"
str.match(reg) // ['abc', 'bc', index: 1, input: '3abc4,5abc6', groups: undefined]

受参数 g 的影响

var reg = new RegExp("a(bc)", "g")
var str = "3abc4,5abc6"
str.match(reg) // ['abc', 'abc']

matchAll

返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器

const regexp = RegExp('foo[a-z]*','g')
const str = 'table football, foosball'
const matches = str.matchAll(regexp)

for (const match of matches) {
  console.log(match)
}
// ['football', index: 6, input: 'table football, foosball', groups: undefined]
// ['foosball', index: 16, input: 'table football, foosball', groups: undefined]

RegExp必须是设置了全局模式g的形式,否则会抛出异常TypeError

String静态方法

String.fromCharCode()

String.fromCharCode(65, 66, 67); // 返回 "ABC"