string 常用方法


/*
1、charAt 和 charCodeAt
charAt方法和charCodeAt方法都接收一个参数,基于0的字符位置 
charAt方法是以单字符字符串的形式返回给定位置的那个字符 
charCodeAt方法获取到的不是字符而是字符编码 
*/
var str = "Hello world";
console.log(str.charAt(1)); // e
console.log(str.charCodeAt(1)); // 101
console.log(str[1]); // e

/* 2、concat */
var str = "hello ";
var res = str.concat("world");
console.log(res); // hello world
console.log(str); // hello
var res1 = str.concat("nihao","!");
console.log(res1); // hello nihao!

/* 3、
slice方法:第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
substring方法:第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
substr方法:第一个参数指定子字符串开始位置,第二个参数表示返回的字符个数 
这三个方法都会返回被操作字符串的一个子字符串,都接收一或两个参数 
如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。这些方法也不会修改字符串本身,只是返回一个基本类型的字符串值 
*/
var str = "Hello world";
console.log(str.slice(3)); //lo world 
console.log(str.substring(3)); //lo world 
console.log(str.substr(3)); //lo world

console.log(str.slice(3,7)); //lo w  7表示子字符串最后一个字符后面的位置,简单理解就是包含头不包含尾 
console.log(str.substring(3,7)); //lo w
console.log(str.substr(3,7)); //lo worl 7表示返回7个字符

console.log(str.slice(3,-4)); //lo w  -4+11=7表示子字符串最后一个字符后面的位置  简单理解就是包含头不包含尾
console.log(str.substring(3,-4)); //hel  会转换为console.log(str.substring(3,0)); 
console.log(str.substr(3,-4)); 
//此外由于这个方法会将较小数作为开始位置,较大数作为结束位置,所以相当于调用console.log(str.substring(0,3));

/* 4、
indexOf方法和lastIndexOf方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置,如果没有找到,则返回-1 
indexOf方法是从字符串的开头向后搜索子字符串,lastIndexOf方法正好相反 
这两个方法都可以接收两个参数:要查找的子字符串和查找的位置 
*/
var str = "hello world";
console.log(str.indexOf("o")); // 4
console.log(str.lastIndexOf("o")); // 7
console.log(str.indexOf("o",6)); // 7
console.log(str.lastIndexOf("o",6)); // 4/* 5、trim方法用来删除字符串前后的空格 */
var str = "     hello world     ";
console.log('(' + str.trim() + ')');
console.log('(' + str + ')');
console.log(str.length);

posted @ 2019-01-03 12:00  sfornt  阅读(157)  评论(0编辑  收藏  举报