js字符串

charAt方法和charCodeAt方法都接收一个参数,字符串中第一个字符下标为0
charAt方法是以单字符字符串的形式返回给定位置的那个字符
charCodeAt方法获取到的不是字符而是字符编码
var str="hello world";
console.log(str.charAt(1)); 显示为第一个字符
console.log(str.charCodeAt(1)); 显示为字符编码
console.log (str.charAt(str.length-1));
还可以使用方括号加数字索引来访问字符串中特定字符          console.log(str[1]);
 
字符串操作方法
concat方法 concat方法是专门用拼接字符串的
var str="hello"
var res=str.concat("world");
console.log(res);
console.log(str); 这说明原来字符串的值没有变
var res1=sre.concat("nihao","!");
console.log(res1); concat可以接受任意多个参数
 
 
slice方法、substring方法、substr方法
slice方法:第一个参数指定字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置
substring方法:第一个参数指定字符串开始的位置,第二个参数表示表示子字符串最后一个字符后面的位置,不接受负的参数
substr方法:第一个参数指定字符串开始的位置,第二个参数表示返回的字符个数
 
这三个方法都会返回被操作字符串的一个子字符串,都接受一或两个参数
如果没有个这三个方法传第二个参数,则将字符串长度为结束位置,这些字符串不会修改字符串本身,只是返回一个基本类型的字符串值
 
 
var str="hello would";
console.log(str.slice(3));
console.log(str.substring(3));
console.log(str.substr(3));
 
 
console.log(str.slice(3,7));
7表示子字符串最后一个字符后面的位置 简单理解就是包含头不包含尾
显示为lo w
 
console.log(str.substring(3,7));
显示为lo w
 
console.log(str.substr(3,7)); 7表示返回7个字符
显示为lo worl
 
 
console.log(str.slice(3,-4));
lo w -4+11=7表示子字符串最后一个字符后面的位置 简单理解就是包含头不包含尾
console.log(str.substring(3,-4));
hel 会转换为console.log(str.s所以相当于调用consoleubstring(3,0));
此外由于这个方法会将较小数作为开始位置,较大数作为结束位置,.log(str.substring(0,3));
console.log(str.substr(3,-4)); ""空字符串
 
 
字符串位置方法
indexOf方法和lastIndexOf方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置,如果没有找到,则返回-1
indexOf方法是从字符串的开头向后搜索子字符串,lastIndexOf方法正好相反
这两个方法都可以接收两个参数:要查找的子字符串和查找的位置
lastIndexOf() 方法对大小写敏感! 没有找到,返回-1
 
var str="hello world";
console.log(str.indexOf("o"));显示为4
console.log(str.lastIndexOf("o")); 显示为7
console.log(str.lastIndexOf("Hello")); 显示为-1
console.log(str.indexOf("o",6)); 显示为7
6表示为从第六个开始找
console.log(str.lastIndexOf("o",6));显示为4
6表示为最后一个为第六个,从第0个开始找
 
 
trim方法用来删除字符串前后的空格
var str=" hello world ";
console.log(str.trim());
console.log('('+str+')');
 
大小写转换
var str="HELLO world";
console.log(str.toLowerCase()); 小写
console.log(str.toUpperCase()); 大写

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324768790&siteId=291194637