<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> /* 1.字符串操作方法 ---concat() 拼接;直接用 + 加号更省事 ---slice() 截取(开始下标,结束下标)不包含结束索引值 ---substrig() 截取 同slice ---substr() 截取 (开始下标,返回的字符数) */ /* 2.字符串位置方法 ---indexOf() 从字符串开头查找 ---lastIndexOf() 凑够末尾 搜索传入的字符串,并返回位置(如果没找到,则返回-1) */ //实例,查找所有指定字符的位置 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.字符串包含方法 ---startsWith() 开始的字符是否是要检索的元素 ---endsWith() ---includes() 是否包含某个字符,返回boolean类型 */ /* 4.一些其他实用的方法 trim() ---删除前后所有的空格 repeat() ---表示要将字符串复制多少次 padStart()和padEnd() ---分别在原有字符串前后,复制元素 toLowerCase()和toLocaleLowerCase() toUpperCase()和toLocaleUpperCase() ---大小写转换(推荐使用后者,地区特定的转换方法) */ /* 5.字符串模式匹配方法 match() ---等同于正则RegExp对象的exec() search() ---返回模式第一个匹配到的位置索引(没找到就返回-1) replace() ---查找并替换 split() ---根据指定元素,分割字符,返回数组 localeCompare() ---判断字符串先后(按照字母表顺序) */ let text = "cat, bat, sat, fat"; let pattern = /.at/; let matches = text.match(pattern); console.log(matches.index); // 0 console.log(matches[0]); // cat console.log(pattern.lastIndex); // 0 let searchT = text.search(/at/); console.log(searchT); // 1 let result = text.replace("at", "ond"); console.log(result); // cond, bat, sat, fat let result2 = text.replace(/at/g, "ond"); console.log(result2); // cond, bond, sond, fond </script> </body> </html>