字符串
字符串可以包含在单引号,双引号,反引号之中:
let a = 'hello';
let b = 'world';
let c = `hello world`;
复制代码
单引号和双引号其实功能是一样的,反引号可以允许我们通过${...}
将表达式嵌入到字符串中,比如:
function sum(a,b){
return a+b;
}
console.log(`sum(1,2) = 3`)// 1+2 = 3
复制代码
反引号的使用还有一个特点就是允许我们换行,如:
let result = `
hello
world
I
am
coming
`
console.log(result)//输出多行显示
复制代码
如果使用单引号或者双引号这样操作就会出现Error: Unexpected token ILLEGAL
字符串长度
length 属性可以获取字符串长度
alert(`hello`.length);// 5
工作中经常有部分人会错误的使用str.length()
,这样是不对的,length是一个属性,不是函数
字符访问
访问字符有两种方式,一个是使用方括号[pos]
,另一个是使用chartAt(pos)
方法
let str = 'hello';
//访问第一个字符
alert(str[0]); // h
alert(str.charAt(0)); // h
//访问最后一个字符
alert(str[str.length -1]); // o
alert(charAt(str.length -1)); // o
复制代码
两者的区别在于使用[]
未找到对应的字符时返回undefined,而charAt返回空字符串:
let str = 'hello';
alert(str[10]);// undefined
alert(str.charAt(10)); // ''
复制代码
字符串大小写转化
toLowerCase() 和 toUpperCase()可以实现字符串的大小写转化:
alert(`hello`.toUpperCase()); // HELLO
alert(`HELLO`.toLowerCase()); // hello
//仅仅转化字符串中第一个字符
alert(`HELLO[0]`.toLowerCase()); // hELLO
复制代码
字符串查找
str.indexOf(substr,pos)
它是从pos位置开始,从str字符串中查找substr,如果没有找到则返回-1,否则返回相应的字符位置:
let str = 'hello';
alert(str.indexOf('hello')); // 0
alert(str.indexOf('Hello')); // -1
alert(str.indexOf('l')); // 2 该str中包含两个l,返回最先的位置
alert(str.indexOf('l',2)); // 3 l第一次出现的位置是2,此时我们查找下一个位置,从2开始返回3
复制代码
str.lastIndexOf(substr,pos)
它是从pos位置开始,从str字符串的末尾中查找substr,如果没有找到则返回-1,否则返回相应的字符位置:
let str = 'hello';
alert(str.lastIndexOf('hello')); // 0
alert(str.lastIndexOf('Hello')); // -1
alert(str.lastIndexOf('l')); // 1 该str中包含两个l,从末尾开始返回最先的位置
alert(str.lastIndexOf('l',2)); // 2 l第一次出现的位置是2,此时我们查找下一个位置,从2开始返回2
复制代码
str.includes(substr.pos)
它是取决于str是否包含substr返回true或者false
let str = 'hello';
alert(str.includes('hello'));// true
alert(str.includes('world'));// false
alert(str.includes('h',1));// false
alert(str.includes('o',4));// true
复制代码
str.startsWith和str.endsWith
alert( "hello".startsWith("he") ); // true 'hello'是以'he'开始的
alert( "hello".endsWith("lo") ); // true 'hello'是以'lo'结尾的
子字符串获取
JavaScript 中有三种获取字符串的方法:substring、substr 和 slice。
str.substring(start,end)
它返回start和end之间的字符串,不包括end值,允许start大于end,但是不允许负值:
let str = 'helloworld';
alert(str.substring(2,6)); //llow
alert(str.substring(6,2)); //llow
复制代码
str.substr(start,length)
它返回start开始到指定length的字符串部分:
let str = 'helloworld';
alert(str.substr(2,6)); //llowor
alert(str.slice(-6,2)); //ow 表示从右边第六个位置开始获得两个字符
复制代码
str.slice(start,end)
它返回start和end之间的字符串,不包括end值,不允许start大于end,可以允许负值:
let str = 'helloworld';
alert(str.slice(2,6)); //llow
alert(str.slice(6,2)); // "" 返回空字符串
alert(str.slice(-6,-2)); //owor 表示从右边第六个位置开始到右边第二个位置结束
复制代码
总结
有 3 种类型的引号。反引号允许字符串跨越多行并可以在 ${…} 中嵌入表达式。
获取字符时,使用 [] 或者charAt。
获取子字符串,使用 slice 或 substring。
字符串的大/小写转换,使用:toLowerCase/toUpperCase。
查找子字符串时,使用 indexOf 或 includes/startsWith/endsWith 进行简单检查。
字符串还有其他几种有用的方法:
str.trim() —— 删除字符串前后的空格 (“trims”)。
str.repeat(n) —— 重复字符串 n 次。