字符串就是零个或多个排在一起的字符,单引号字符串的内部,可以使用双引号。双引号字符串的内部,可以使用单引号。
"hello world"
'hello world'
"hello 'world'"
'hello "world"'
如果要在单引号字符串的内部,使用单引号,就必须在内部的单引号前面加上反斜杠,用来转义。双引号字符串内部使用双引号,也是如此
"hello \"world\""
注意:字符串默认只能写在一行内,分成多行将会报错。
length属性
length属性返回字符串的长度,该属性是无法改变的。
var txt= "hello world";
console.log(txt.length);
chartAt 字符串方法
charAt 方法返回指定位置的字符,参数是从0开始编号的。
var txt= "hello world";
console.log(txt.charAt(1));
console.log(txt.charAt(txt.length-1));
注意:如果参数为负数,或大于等于字符串的长度,char 返回空字符串
concat 字符串方法
concat方法用于连接两个字符串,返回一个新字符串,不改变原字符串
var txt= "hello";
var txt1="world";
console.log(txt);
console.log(txt1);
console.log(txt.concat(txt1));
concat方法支持多个字符串链接
var txt= "he";
var txt1="llo";
var txt2="wor";
var txt3="ld";
console.log(txt);
console.log(txt1);
console.log(txt2);
console.log(txt3);
console.log(txt.concat(txt1,txt2,txt3));
如果参数不是字符串,conca 方法会将其先转为字符串,然后再连接
var txt= "1";
var txt1=2;
var txt2=3;
var txt3=4;
console.log(txt);
console.log(txt1);
console.log(txt2);
console.log(txt3);
console.log(txt.concat(txt1,txt2,txt3));
substring 字符串方法
subsring 方法用于从原字符串取出子字符串并返回,不改变原字符串。它的第一个参数表示子字符串的开始位置,第二个位置表示结束位置(返回结果不含该位置)
var txt= "hello word";
console.log(txt.substring(0,3));
如果省略第二个参数,则表示子字符串一直到原字符串的结束
var txt= "hello word";
console.log(txt.substring(3));
如果第一个参数大于第二个参数,substing 方法会自动更换两个参数的位置
var txt= "hello word";
console.log(txt.substring(6,1));
如果参数是负数,substring 方法会自动将负数转为0
var txt= "hello word";
console.log(txt.substring(-2,5));
substr 字符串方法
subst 方法用于从原字符串取出子字符串并返回,不改变原字符串,跟 substing 方法的作用相同subsr 方法的第一个参数是子字符串的开始位置(从0开始计算),第二个参数是子字符串的长度。
var txt= "hello word";
console.log(txt.substr(2,5));
如果省略第二个参数,则表示子字符串一直到原字符串的结束
var txt= "hello word";
console.log(txt.substr(2));
如果第一个参数是负数,表示倒数计算的字符位置。如果第二个参数是负数,将被自动转为0,因此会返回空字符串
var txt= "hello word";
console.log(txt.substr(-5));
console.log(txt.substr(2,-3));
indexOf 字符串方法
imndexof方法用于确定一个字符串在另一个字符串中第一次出现的位置,返回结果是匹配开始的位置。如果返回-1,就表示不匹配。
var txt= "hello word";
console.log(txt.indexOf("e"));
console.log(txt.indexOf("a"));
IndexOf方法还可以接受第二个参数,表示从该位置开始向后匹配
var txt= "hello word";
console.log(txt.indexOf("o",4));
trim 字符串方法
trim 方法用于去除字符串两端的空格,返回一个新字符串,不改变原字符串
var txt= " hello word ";
console.log(txt);
console.log(txt.trim());
注意:该方法去除的不仅是空格,还包括制表符(\t,\v)、换行符(\n)和回车符(\r) 。
split 字符串方法
split方法按照给定规则分割字符串,返回一个由分割出来的子字符串组成的数组。
var txt= " hello|word ";
console.log(txt);
console.log(txt.split("|"));
如果分割规则为空字符串,则返回数组的成员是原字符串的每一个字符
var txt= " hello|word ";
console.log(txt);
console.log(txt.split(""));
如果省略参数,则返回数组的唯一成员就是原字符串
var txt= " hello|word ";
console.log(txt);
console.log(txt.split())
split 方法还可以接受第二个参数,限定返回数组的最大成员数。
var txt= " h|ello|wo|rd ";
console.log(txt);
console.log(txt.split("|",2));