JavaScript的字符串就是用' '或者" "括起来的字符;
如果 ' 本身也是一个字符,那就可以用" "括起来,比如" I
' m fine
"包含的字符是I
,' ,m
,空格,f
,i,n,e
这8个字符;
如果字符串内部既包含 ' 又包含 " 怎么办?可以用转义字符\
来标识;
'I\'m \"fine\"!'
//字符串内容I'm "fine"!
在字符串中嵌入变量需要用+来拼接字符串和变量:
var name = 'zhangsan';
var age = 23;
console.log('My name is'+ name +'and my age is'+ age +'years old')
//My name is zhangsan and my age is 23 years old
es6新引入了模板字符串,就是用反引号` `来标识。它既可以当作普通字符串来使用,也可以用来定义多行字符串,或者在字符串中嵌入变量
var name = `zhangsan`;
var age = 23;
console.log(`My name is ${name}
and my age is ${age} years old`)
//My name is zhangsan and my age is 23 years old
字符串的一些操作方法:
- length,可以获取字符串的长度,字符串和数组有相似的索引,索引号从0开始,特别注意的是,字符串是不可变的,所以通过索引号对字符串进行修改赋值是没有效果的
var str = 'Hello,World!'
str.length; //12
str[3]; //'l'
str[1] = 'x';
console.log(str); //Hello,world!
- toUpperCase()将字符串全部转换为大写
var str = 'Hello';
str.toUpperCase;
console.log(str); //HELLO
- toLowerCase()将字符串全部转换为小写
var str = 'HELLO';
str.toLowerCase;
console.log(str); //hello
- indexOf()搜索指定字符串出现的位置
var str = 'hello,world'
console.log(str.indexOf('w')) //返回索引号6
console.log(str.indexOf('b')) //没有找到指定字符,返回-1
- substring()截取,返回指定索引区间的字符串
var str = 'hello,world';
console.log(str.substring(0,5)); //从索引0开始,到5结束,不包括5,返回hello
console.log(str.substring(6)); //从索引6开始,到末尾结束,返回world
console.log(str); //substring()不改变原字符串,返回hello,world