js common method string operations (1)

String type

Create an instance of type String

var stringObject = new String("hello world");

String type of property

length;// 字符串的长度 注意:即使字符串包含双字节字符,这种双字节字符也算为一个字符

valueOf(), toLocaleString(), toString()

// 继承的`valueOf()`,`toLocaleString()`,`toStirng()`方法,都会返回对象所表示的基本类型字符串值.

charAt() Access the string of characters with index

var stirngValue = "hello world";
stirngValue.charAt(1);// "e"

Use square brackets notation to access the characters stringValue[1]also have access to"e"

charCodeAt() Access the string of characters encoded with index

var stringValue = "hello world";
stirngValue.charCodeAt(1);// "101"

concat()One or more strings together

var stringValue = "hello ";
var res = StringValue.concat("world");
res;// "hello world"
stringValue;// "hello "

var StringValue = "hello ";
var res = stringValue.concat("world", "!");
res;// "hello world!"
stringValue;// "hello"
// 但在大多数情况下,还是使用 + 操作符来拼接字符串更为方便

slice(), substr(), substring()

var strValue = "hello world";
// 传递一个正参数
// 从索引为3的位置一致截到最后
strValue.slice(3);// "lo world"
strValue.substring(3);// "lo world"
strValue.substr(3);// "lo world"

// 传递两个正数参数
strValue.slice(3, 7);// "lo w" 第二个参数是索引位置(不包含)
strValue.substring(3, 7);// "lo w" 第二个参数是索引位置(不包含)
strValue.substr(3, 7);// "lo worl" 第二个参数是长度

// 传递一个负参数
strValue.slice(-3);// "rld"
strValue.substring(-3);// "hello world"
strValue.substr(-3);// "rld"

// 第二个传递负参数,表示倒数第几个
// 同时也可以这样认为:字符串长度加参数 11 + (-3) = 8 8是索引位置
strValue.slice(3, -4);// "lo w" 第二个参数是索引位置(不包含)
strValue.substring(3, -4);// "hel" 第二个参数是索引位置(不包含)
strValue.substr(3, -4);// "" 长度无法为负

indexOf(),lastIndexOf

The former left to right, the latter from right to left to find the location of the string is returned if the string is not found is returned-1

var strValue = "hello world";
strValue.indexOf("o");// 4
strValue.lastIndexOf("o");// 7

strValue.indexOf("o", 6);// 7
strValue.lastIndexOf("o", 6);// 4

trim()

Create a copy of a string, remove all spaces front and suffix, and then returns the result

var strValue = "   hello world   ";
var strValueBak = strValue.trim();// "hello world"

Guess you like

Origin www.cnblogs.com/zxcv123/p/12037628.html