一些字符串对象的方法,内有注释
<!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>字符串对象</title>
</head>
<body>
<script>
var str = 'we are dha hdashdfio aljd shidh aoi chain';
var res = str.toUpperCase();
console.log(res); //返回全部字母大写
console.log(str);
res = res.toLowerCase();
console.log(res); //返回全部字母小写
res = str.indexOf('a');
console.log(res); //3 返回第一次出现的索引
res = str.lastIndexOf('a');
console.log(res); //38 返回第一次出现的索引
res = str.indexOf('e',2);
console.log(res); //5 返回下表为2后第一次出现的'e'
res = str.length;
console.log(res); //41 返回字符串长度
res = str.charAt(39);
console.log(res); //i 返回目标索引的值
str = 'we are dha hdashdfio aljd shidh aoi chain dha';
res = str.search('dha');
console.log(res); //7 返回指定字符串第一次出现的位置
res = str.slice(4,8);
console.log(res); //re d以[4,8)方式返回切片值,可以用负值,返回切片值
res = str.substring(4,8);
console.log(res); //re d以[4,8)方式,不能用负值下标
res = str.substr(4,8);
console.log(res); //re dha h 第一个值4是起始索引,第二个值8是切片长度
str = "Please visit Microsoft and Microsoft!";
res = str.replace("Microsoft", "W3School");//用另一个值替换在字符串中指定的值,只替换首个匹配,返回替换结束的整句话
console.log(res);
str = "Please visit Microsoft!";
res = str.replace("MICROSOFT", "W3School");//对大小写敏感,不匹配
console.log(res); //==>Please visit Microsoft!
//使得对大小写敏感,用正则表达式/i
str = "Please visit Microsoft!";
res = str.replace(/MICROSOFT/i, "W3School"); //可以匹配并且替换
console.log(res); //==>Please visit W3School!
//替换所有匹配的值
str = "Please visit Microsoft and Microsoft!";
res = str.replace(/Microsoft/g,'W3School');
console.log(res); //Please visit W3School and W3School!
var text1 = "Hello";
var text2 = "World";
res = text1.concat(' ',text2);
console.log(res); //Hello World 连接字符串
str = " Hello World! ";
res = str.trim();
console.log(res); //去除字符串两侧的空格
var txt = "a,b,c,d,e";
res = txt.split(',');
console.log(res);//['a', 'b', 'c', 'd', 'e'] 以','为分割转成数组
res = txt.split(' ');
console.log(res); //['a,b,c,d,e'] 以空格分割
</script>
</body>
</html>