js字符串操作方法

1.字符方法:

   str.charAt(): 可以访问字符串中特定的字符,可以接受0至字符串长度-1的数字作为参数,返回该位置下的字符,如果参数超出该范围,返回空字符串,如果没有参数,返回位置为0的字符;

   str.charCodeAt(): 和charAt()用法一样,不同的是charCodeAt()返回的是字符编码而不是字符。

var  anyString="hello tino";
anyString.charAt()   //"h"
anyString.charAt(2)   //"l"
anyString.charAt(18)   //""

2.字符串操作方法:

   字符串拼接:

   最常用的就是字符串拼接,可以用"+“操作符连接两个字符串,或者用concat()方法,concat()方法接受一个或多个字符串参数,返回拼接后得到的新字符串,需要注意的是concat()方法不改变原字符串的值。

var str="hello tino";
var nstr=str.concat(" and nick");   
console.log(str);  // “hello tino”
console.log(nstr);  // "hello tino and nick"

基于子字符串创建新字符串:

slice() 接受一到两个参数,第一个参数是指定字符串的开始位置,第二个参数是字符串到哪里结束(返回的字符串不包括该位置),如果没有第二个参数,则将字符串的末尾作为结束位置。如果不传参数,返回原字符串。slice()方法也不会改变原有字符串

var str="hello tino";
str.slice(5,9)    // "tino"
str.slice(5)      //"tino"
str.slice()       //"hello tino"

substr()方法和slice()方法一样,不同在于参数是负值时,slice()方法会将传入的负值与字符串长度相加,substr()会将第一个负值相加,第二个负值参数转换为0;

var str="hello tino";
console.log(str.slice(-4));       // "tino"
console.log(str.substr(-4));      //"tino"
console.log(str.slice(1,-4));     //"ell"
console.log(str.substr(1,-4));    // ""

substring()方法也接受两个参数,与前两不同,substring()第二个参数是表示字符的个数。

3.字符串位置方法:

indexOf(),参数为子字符串,从左至右查找,返回子字符串位置,如果没找到该子字符串,返回-1。

lastIndexOf(),参数为子字符串,从右至左查找,返回子字符串位置,如果没找到该子字符串,返回-1。

这两个方法接受可选的第二个参数(整数),表示从该位置开始搜索。

var str="hello tino";
str.indexOf("o")    //4
str.lastIndexOf("o")  //9

4.trim()方法

该方法创建一个字符串的副本,删除前置和后缀的所有空格。

5.大小写转换

toLowerCase() ,创建原字符串的小写副本

toUpperCase() ,创建原字符串的大写副本

原文地址:https://www.cnblogs.com/renbo/p/7823492.html