JavaScript: 关于字符串对象的八个方法
方法 | 作用 |
---|---|
charAt(索引) | 根据索引查找对应字符,找不到就返回空字符串 |
charCodeAt(索引) | 根据索引查找对应字符的ASCII码,找不到就返回NaN |
indexOf(元素) | 查找元素在字符串中的索引下标,没有就返回 -1 |
split(内容) | 字符串根据指定内容分割,形成一个数组 |
substring(索引1,索引2) | 截取两个索引之间的所有元素 |
substr(起始索引,截取的个数) | 从起始索引开始截取对应的个数 |
toLowerCase() | 将字符串的元素转为小写 |
toUpperCase | 将字符串的元素转为大写 |
replace(被替换的内容,替换的内容) | 将字符串的部分内容进行替换 |
注: 这些方法都不会改变原字符串的内容
一、charAt(索引)
根据索引查找在字符串中的对应字符,如果找不到则返回空字符串
var str = "helloworld";
//查找第6个字符
var res = str.charAt(5); // w
console.log(res);
//查找第20个字符,由于没有这个字符
var res1 = str.charAt(19); // 控制台什么都不显示,表示输出空字符串
console.log(res1);
//不改变原字符串
console.log(str); //helloworld
二、charCodeAt(索引)
根据索引查找在字符串中的对应字符的ASCII码,如果找不到则返回NaN
var str = "helloworld";
//查找第6个字符,返回值为该元素对应的ASCII码
var res = str.charCodeAt(5); // 119
console.log(res);
//查找第20个字符,由于没有这个字符,输出NaN
var res1 = str.charCodeAt(19); // NaN
console.log(res1);
//不改变原字符串
console.log(str); //helloworld
三、indexOf(字符)
根据字符查找在字符串中出现的位置的索引,如果找不到则返回 - 1
var str = "helloworld";
//查找字符 w 第一次出现的位置的索引下标
var res1 = str.indexOf("w"); // 5
console.log(res1);
//查找字符 z , 由于没有这个字符,返回 -1
var res2 = str.indexOf("z"); // -1
console.log(res2);
//不改变原字符串
console.log(str); //helloworld
indexOf(字符,起始索引)
根据字符从起始索引位置开始往后查找字符串出现位置的索引,如果找不到则返回 - 1
var str = "helloworld";
//从字符 w 之后开始对字符 o 进行查找,返回o的索引值
var res = str.indexOf("o",5); //6
console.log(res);
//不改变原字符串
console.log(str); //helloworld
四、split(字符)
将字符串根据指定的字符进行分割,拼成一个数组
var str = "helloworld";
//根据字符o将整个字符串分成三部分
var res = str.split("o"); // ["hell", "w", "rld"]
console.log(res);
//不改变原字符串
console.log(str); //helloworld
五、substring(索引1, 索引2)
截取两个索引之间的所有字符
var str = "helloworld";
//截取的字符包括大索引值的那个,不包括小索引值的那个
//截取第2个字符到第6个字符之间的所有字符,包括第2个字符但不包括第6个字符
var res1 = str.substring(1,5) // ello
console.log(res1);
var res2 = str.substring(5,1) // ello
console.log(res2);
//只有一个索引就表示截取掉从这个索引开始到最后
var res3 = str.substring(1) // elloworld
//不改变原字符串
console.log(str); //helloworld
六、substr(起始索引,截取个数)
从起始索引开始,往后截取字符
var str = "helloworld";
//截取掉第5个字符之后的3个字符(包括第4个字符)
var res = str.substr(4,3) // owo
console.log(res);
//不改变原字符串
console.log(str); //helloworld
七、toUpperCase() 和 toLowerCase()
toUpperCase() : 将字符串中的所有字符转为大写
toLowerCase() : 将字符串中的所有字符转为小写
var str = "HelloWorld"
//将字符转为大写
var res1 = str.toUpperCase(); // HELLOWORLD
console.log(res1);
//将字符转为小写
var res2 = str.toLowerCase(); //helloworld
console.log(res2);
//不改变原字符串
console.log(str); //HelloWorld
八、replace(被替换的内容,替换的内容)
将字符串中的部分字符进行替换
var str = "helloworld";
//用 WORLD 替换 world
var res = str.replace("world","WORLD"); // helloWORLD
console.log(res);
//不改变原字符串
console.log(str); //helloworld