String是对应字符串的引用类型、
本文缺少charAt()方法、charCodeAt()方法、fromCharCode()方法介绍,后续用到再补充。
字符串操作方法
slice()、substr()、substring()
-
slice():
第一个参数:截取的开始位置
第二个参数:截取的结束位置(不包括该位置)
负参:字符串长度加上负参值
-
substr():
第一个参数:截取的开始位置
第二个参数:截取的个数
负参:第一个负参当作字符串长度加上负参值
第二个负参当作0
-
substring():
第一个参数:截取的开始位置
第二个参数:截取的结束位置(不包括该位置)
负参:0
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" 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)
字符串位置方法
indexOf()、lastIndexOf()
- indexOf():从头检索。第二个参数代表开始搜索的位置
- lastIndexOf():从尾检索。第二个参数代表开始搜索的位置
*使用第二个参数并循环调用 indexOf() 或lastIndexOf() ,可以在字符串中找到所有的目标子字符串*
let stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
let positions = new Array();
let pos = stringValue.indexOf("e");
while(pos > -1) {
positions.push(pos);
pos = stringValue.indexOf("e", pos + 1);
}
console.log(positions); // [3,24,32,35,52]
字符串包含方法
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
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
trim()
这个方法会创建字符串的一个副本,删除前、后所有空格符,再返回结果,原始字符串不受影响
trimeLeft() 和 trimRight() 方法分别用于从字符串开始和末尾清理空格符
padStart()、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......"
字符串迭代与解构
字符串的原型上暴露了一个 @@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()
toLocaleLowerCase() 和toLocaleUpperCase() 方法旨在基于特定地区实现。
字符串模式匹配方法
match()
这个方法本质上跟 RegExp 对象的 exec()方法相同。 match() 方法接收一个参数,可以是一个正则表达式字符串,也可以是一个 RegExp 对象
let text = "cat, bat, sat, fat";
let pattern = /.at/;
// 等价于pattern.exec(text)
let matches = text.match(pattern);
console.log(matches.index); // 0
console.log(matches[0]); // "cat"
console.log(pattern.lastIndex); // 0
match() 方法返回的数组与 RegExp 对象的 exec() 方法返回的数组是一样的:第一个元素是与整个模式匹配的字符串,其余元素则是与表达式中的捕获组匹配的字符串(如果有的话)。
let text = "mom and dad and baby";
let pattern = /mom( and dad( and baby)?)?/gi;
let matches = pattern.exec(text);
console.log(matches.index); // 0
console.log(matches.input); // "mom and dad and baby"
console.log(matches[0]); // "mom and dad andbaby"
console.log(matches[1]); // " and dad and baby"
console.log(matches[2]); // " and baby"
search()
这个方法唯一的参数与match() 方法一样:正则表达式字符串或 RegExp 对象。这个方法返回第一个匹配的位置索引,如果没找到则返回-1。 search()始终从字符串开头向后匹配模式。
let text = "cat, bat, sat, fat";
let pos = text.search(/at/);
console.log(pos); // 1
replace()
这个方法接收两个参数
-
第一个参数:可以是一个 RegExp 对象或一个字符串
第一个参数是字符串,那么只会替换第一个子字符串
要想替换所有子字符串,第一个参数必须为正则表达式并且带全局标记
let text = "cat, bat, sat, fat"; let result = text.replace("at", "ond"); console.log(result); // "cond, bat, sat, fat" result = text.replace(/at/g, "ond"); console.log(result); // "cond, bond, sond, fond"
-
第二个参数:可以是一个字符串或一个函数
第二个参数是字符串的情况下,有几个特殊的字符序列,可以用来插入正则表达式操作的值:
字符序列 | 替换文本 |
---|---|
$$ | $ |
$& | 匹配整个模式的子字符串。与 RegExp.lastMatch相同 |
$’ | 匹配的子字符串之后的字符串。与RegExp.rightContext 相同 |
$` | 匹配的子字符串之前的字符串。与RegExp.leftContext 相同 |
$n | 匹配第 n 个捕获组的字符串,其中 n 是0~9。比如,$1是匹配第一个捕获组的字符串,$2 是匹配第二个捕获组的字符串,以此类推。如果没有捕获组,则值为空字符串 |
$nn | 匹配第 nn 个捕获组字符串,其中 nn 是01~99。比如,$1是匹配第一个捕获组的字符串, $02 是匹配第二个捕获组的字符串,以此类推。如果没有捕获组,则值为空字符串 |
使用这些特殊的序列,可以在替换文本中使用之前匹配的内容,如下面的例子所示:
let text = "cat, bat, sat, fat";
result = text.replace(/(.at)/g, "word ($1)");
console.log(result); // word (cat), word (bat), word (sat), word (fat)
//这里,每个以 "at" 结尾的词都会被替换成 "word" 后跟一对小括号,其中包含捕获组匹配的内容 $1 。
第二个参数可以是一个函数。在只有一个匹配项时,这个函数会收到3个参数:与整个模式匹配的字符串、匹配项在字符串中的开始位置,以及整个字符串。在有多个捕获组的情况下,每个匹配捕获组的字符串也会作为参数传给这个函数,但最后两个参数还是与整个模式匹配的开始位置和原始字符串。这个函数应该返回一个字符串,表示应该把匹配项替换成什么。使用函数作为第二个参数可以更细致地控制替换过程,如下所示:
function htmlEscape(text) {
return text.replace(/[<>"&]/g, function(match,
pos, originalText) {
switch(match) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
// "<p class="greeting">Helloworld!</p>"
这里,函数 htmlEscape() 用于将一段HTML中的4个字符替换成对应的实体:小于号、大于号、和号,还有双引号(都必须经过转义)。实现这个任务最简单的办法就是用一个正则表达式查找这些字符,然后定义一个函数,根据匹配的每个字符分别返回特定的HTML实体
split()
根据传入的分隔符将字符串拆分成数组
作为分隔符的参数可以是字符串,也可以是 RegExp 对象
第二个参数即数组大小,确保返回的数组不会超过指定大小
let colorText = "red,blue,green,yellow";
let colors1 = colorText.split(","); // ["red", "blue", "green", "yellow"]
let colors2 = colorText.split(",", 2); // ["red", "blue"]
let colors3 = colorText.split(/[^,]+/); // ["",",", ",", ",", ""]
最后,使用正则表达式可以得到一个包含逗号的数组。注意在最后一次调用 split() 时,返回的数组前后包含两个空字符串。这是因为正则表达式指定的分隔符出现在了字符串开头( “red” )和末尾( “yellow” )。
通俗理解:在字符串的分隔符位置这里砍一刀,砍下的片段被放入数组。而被我砍的地方本身不会进入数组。这里的分隔符是“除了逗号以外的字符”,所以会在“red”、“blue”等地方砍下去。但是注意,如果砍了字符串头部和尾部,会多出来两个空串,好比这里多了一条缝。
localeCompare()
这个方法比较两个字符串,返回如下3个值中的一个:
- 如果按照字母表顺序,字符串应该排在字符串参数前头,则返回负值。(通常是 -1 ,具体还要看与实际值相关的实现。)
- 如果字符串与字符串参数相等,则返回 0 。
- 如果按照字母表顺序,字符串应该排在字符串参数后头,则返回正值。(通常是 1 ,具体还要看与实际值相关的实现。)
let stringValue = "yellow";
console.log(stringValue.localeCompare("brick"));// 1
console.log(stringValue.localeCompare("yellow"));// 0
console.log(stringValue.localeCompare("zoo"));// -1
强调一下,因为返回的具体值可能因具体实现而异,所以最好像下面的示例中一样使用 localeCompare() :
function determineOrder(value) {
let result = stringValue.localeCompare(value);
if (result < 0) {
console.log(`The string 'yellow' comes before the string '${value}'.`);
} else if (result > 0) {
console.log(`The string 'yellow' comes after the string '${value}'.`);
} else {
console.log(`The string 'yellow' is equal to the string '${value}'.`);
}
}
determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
通俗理解:大于就一定是返回正值,小于就一定是返回负值,具体正几负几不知道,它不重要。
在美国,英语是ECMAScript实现的标准语言, localeCompare() 区分大小写,大写字母排在小写字母前面。但其他地区未必是这种情况。