要学习字符串方法,首先要定义一个字符串:
基本语法:
var str = “字符串内容”;
这样一个字符串就被定义完成了,可以进行接下来的学习了
字符串方法:
方法 | 作用 |
---|---|
charAt() | 返回字符串中指定字符的位置(下标索引从0开始) |
concat() | 连接连个字符串 |
indexOf() | 返回指定字符的下标号(下标索引从0开始) |
replace() | 替换掉指定的字符串 |
slice() | 提取指定字符串片段 |
split() | 将字符串分割成数组 |
substr() | 从指定的位置开始,提取指定数量的字符组成新的字符串 |
substring() | 提取两个索引号之间的字符组成新的字符串 |
toUpperCase() | 将字符转为大写形式 |
toLowerCase() | 将字符转为小写形式 |
match() | 查找字符串中字符 |
includes() | 查找字符,返回布尔值(true/false) |
实例如下:
var str = "hello";
var str1 = "javascript"
var str2 = "WORD";
//charAt()
console.log(str.charAt(1));//e
//concat()
console.log(str.concat(str1));//hellojavascript
//indexOf()
console.log(str.indexOf("e"));//1
//replace()
console.log(str.replace("hello","word"));//word
//slice()
console.log(str.slice(0,5));//hello 提取第0位到第5位字符
console.log(str.slice(-5,-1));//hell 倒数第5位到倒数第1位(不包含倒数第1位)
//split()
console.log(str.split(""));//数组形式:["h", "e", "l", "l", "o"]
//substr()
console.log(str.substr(0,2));//he 从下标0开始往后数两位
//substring()
console.log(str.substring(0,2));//he 下标0到下标2
//toUpperCase()
console.log(str.toUpperCase());//HELLO
//toLowerCase()
console.log(str2.toLowerCase());//word
//match()
console.log(str.match("he"));//he
//includes()
console.log(str.includes("he"));//true
以上就是常用的字符串对象了,大家一起加油,学好js!