String 方法
String 方法
所有字符串方法都会返回新字符串。不会修改原始字符串
字符串不能改变,只能替换
查找字符串中的字符串
indexOf() 方法返回字符串中指定文本首次出现的索引
var str = "This is why we why!";
var pos = str.indexOf('why'); //8
lastIndexOf() 方法查找字符串最后一次出现的地方
var str = "This is why we why!";
var text = str.lastIndexOf('why'); //15
两种方法都接受作为检索起始位置的第二个参数
检索字符串中的字符串
search() 方法搜索特定值的字符串,并返回匹配的位置
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate"); //17
- search() 方法无法设置第二个开始位置参数
- indexOf() 方法无法设置更强大的搜索值(正则表达式)
提取部分字符串
slice() 方法
slice() 提取字符串的某个部分并在新字符串中返回被提取的部分
var str = "Apple, Banana, Mango";
var res = str.slice(7,13); //Banana
如果某个参数为负,则从字符串的结尾开始计数
如果省略第二个参数,则将裁剪字符串的剩余部分
substring() 方法
substring() 无法接受负的索引
var str = "Apple, Banana, Mango";
var res = str.substring(7,13); //Banana
substr() 方法
substr() 第二个参数规定被提取部分的长度
var str = "Apple, Banana, Mango";
var res = str.substr(7,6); //Banana
第二个参数不能为负,因为它定义的是长度
替换字符串内容
replace() 方法用另一个值替换在字符串中指定的值
默认地,replace() 只替换首个匹配
str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3School"); //Please visit W3School and Microsoft!
如需执行大小写不敏感的替换,则使用/i (大小写不敏感)
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3School"); //Please visit W3School!
如需替换所有匹配,则使用/g 标志(用于全局搜索)
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3School"); //Please visit W3School and W3School!
转换为大写和小写
通过toUpperCase() 把字符串转换为大写
var text1 = "Hello World!"; // 字符串
var text2 = text1.toUpperCase(); // text2 是被转换为大写的 text1
通过toLowerCase() 把字符串转换为小写
var text1 = "Hello World!"; // 字符串
var text2 = text1.toLowerCase(); // text2 是被转换为小写的 text1
concat() 方法
concat() 连接两个或多个字符串
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2); //Hello World
concat()方法可用于代替加运算符
String.trim()
trim() 方法删除字符串两端的空白符
var str = " Hello World! ";
alert(str.trim()); //Hello World!
提取字符串字符
charAt() 方法
charAt() 方法返回字符串中指定下标的字符串
var str = "HELLO WORLD";
str.charAt(0); // 返回 H
chatCodeAt() 方法
charCodeAt() 方法返回字符串中指定索引的字符 Unicode 编码
var str = "HELLO WORLD";
str.charCodeAt(0); // 返回 72
把字符串转换为数组
可以通过split() 将字符转换为数组
var txt = "a,b,c,d,e"; // 字符串
txt.split(","); // 用逗号分隔
txt.split(" "); // 用空格分隔
txt.split("|"); // 用竖线分隔
如果分隔符是 "",被返回的数组将是间隔单个字符的数组
var txt = "Hello"; // 字符串
txt.split(""); // 分隔为字符
String.match()
match() 方法根据正则表达式在字符串中搜索匹配项,并将匹配项作为 Array 对象返回
let text = "The rain in SPAIN stays mainly in the plain";
document.getElementById('demo').innerHTML = text.match(/ain/gi);
输出结果:
ain,ain,ain
String.includes()
如果字符串包含指定值,includes() 方法返回true
let text = "Hello world, welcome to the universe.";
text.includes("world") // 返回 true
String.startsWith()
如果字符串以指定值开头,则starWith() 方法返回true ,否则返回false
let text = "Hello world, welcome to the universe.";
text.startsWith("world", 6) // 返回 true
String.endsWith()
如果字符串以指定值结尾,则endWith() 方法返回true ,否则返回false
let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11) // 返回 true

浙公网安备 33010602011771号