javascript常见字符串操作和数组操作

     常用的字符串方法和数组操作,整理下方便自己以后查阅。

  • 字符串操作

         常用的方法有:

              charAt()、charCodeAt()、concat()、 slice()、 substr()、 substring()、 indexOf()、 lastIndexOf()、 trim()、 toLowerCase()、 toLocaleLowerCase()、 toUpperCase()、 toLocaleUpperCase()。

         与正则有关的方法有:

              match(),search(),replace()、split()

     

 1 // charAt(),charCodeAt()这两个方法分别返回给定位置的字符和字符编码
 2 var chart_str = 'hello world!';
 3 chart_str.charAt(0);//'h'
 4 chart_str.charCodeAt(0);//104
 5 chart_str.charAt(14);//'',越界会返回空字符
 6 chart_str.charCodeAt(0);//NaN
 7 //concat()字符串连接操作
 8 var concat_str = 'hello';
 9 concat_str.concat('!');//'hello !'返回连接后的新的字符串,等价字符串+操作
10 concat_str;//'hello' 做concat操作后,源不会改变
11 concat_str.concat(' ', 'world', '!');//"hello world!"可接收多个参数
12 concat_str.concat([1,2,3]);//"hello1,2,3",传入对象,会调用toString()方法后在操作
13 //indexOf(),lastIndexOf()返回给定字符串所在的开始位置,可传入两个参数,第一个参数表示要查询的子串,第二参数表示从什么位置开始查,省略默认0,查到返回开始位置,否者-1
14 index_str= 'hello world!';
15 index_str.indexOf('hello');//0
16 index_str.lastIndexOf('hello');//0
17 index_str.indexOf('hello',0)//0
18 index_str.indexOf('hello',1);//-1
19 //trim()去除左右空格,等价replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g,'')
20 var trim_str = ' hello  ';
21 trim_str.trim();//'hello'
22 trim_str.trimRight();//非标准
23 trim_str.trimLeft();//非标准
24 //toLowerCase()、 toLocaleLowerCase()、 toUpperCase()、 toLocaleUpperCase()大小写转换,toLocaleLowerCase()、 toLocaleUpperCase()针对于特殊地区,大部分情况和toLowerCase(),toUpperCase()结果一样
25 var case_str = 'hello';
26 case_str.toUpperCase();//'HELLO'
27 case_str.toUpperCase().toLowerCase();//'hello'
28 //split()字符串分割 
29 /**
30 E8 及之前版本会忽略捕获组。 ECMA-262 规定应该把捕获组拼接到结果数组中。 IE9 能正确地
31 在结果中包含捕获组。
32 Firefox 3.6 及之前版本在捕获组未找到匹配项时,会在结果数组中包含空字符串; ECMA-262 规
33 定没有匹配项的捕获组在结果数组中应该用 undefined 表示。
34 */
35 var colorText = "red,blue,green,yellow";
36 var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
37 var colors2 = colorText.split(",", 2); //["red", "blue"] 第二参数限制了项数
38 var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
39 //match()匹配 
40 var match_str = 'hello world! this is test';
41 var matchs = match_str.match(/.is/);//返回一个数组
42 matchs.length;//1
43 matchs[0];//'tis'
44 //search()搜索。search()方法返回字符串中第一个匹配项的索引;如果没
45 //有找到匹配项,则返回-1。
46 var search_text = "cat, bat, sat, fat";
47 text.search(/at/);//1
48 /**
49 replace()替换
50 es提供特殊字符序列
51 字符序列 替换字符
52 $$      $
53 $&      匹配整个模式的子字符串。与RegExp.lastMatch的值相同
54 $'      匹配的子字符串之前的子字符串。与RegExp.leftContext的值相同
55 $`      匹配的子字符串之后的子字符串。与RegExp.rightContext的值相同
56 $n      匹配第n个捕获组的子字符串,其中n等于0~9。例如, $1是匹配第一个捕获组的子字符串,
57         $2是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串
58 $nn     匹配第nn个捕获组的子字符串,其中nn等于01~99。例如, $01是匹配第一个捕获组的子字符串, 
59         $02是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串
60 */
61 var replacet_str = "cat, bat, sat, fat";
62 replacet_str.replace(/(.at)/g, "word ($1)");//"word (cat), word (bat), word (sat), word (fat)"
63 replacet_str.replace(/(.at)/g, "word ($$)");//"word ($), word ($), word ($), word ($)"
64 replacet_str.replace(/(.at)/g, "word ($')");//"word (, bat, sat, fat), word (, sat, fat), word (, fat), word ()"
65 replacet_str.replace(/(.at)/g, "word ($`)");//"word (), word (cat, ), word (cat, bat, ), word (cat, bat, sat, )"
66 /**
67 slice()、 substr()、 substring()
68 这三个方法都返回被操作字符串的子集的,不会改变被操作字符串,接受两个参数,第二参数可省略默认是字符的长度
69 第一个参数表示开始位置,第二个参数表示结束位置。substr()第二参数表示个数,而substring()和slice()第二个
70 参数表示子集最后一个字符的下个位置
71 */
72 //slice()参数为负值时候会和字符串长度相加,参数规整后第一个参数必须小于第二个参数
73 var _str = 'hello world!';
74 _str.slice(2);//"llo world!"
75 _str.slice(-2);//"d!"
76 _str.slice(2,-7);//"llo"
77 _str.slice(-2,-7);//''
78 _str.slice(-7,7);//" w"
79 _str.slice(-7,-2);//" worl"
80 //substr() 第一个参数为负的时候与字符串长度求和,第二个参数为负置为0
81 _str.substr(2);//"llo world!"
82 _str.substr(-2);//"d!"
83 _str.substr(2,-7);//""
84 _str.substr(-2,-7);//''
85 _str.substr(-7,7);//" world!"
86 _str.substr(-7,-2);//" "
87 //substring() 参数为负置为0,参数大的作为结束位置,小的作为开始位置
88 _str.substring(2);//"llo world!"
89 _str.substring(-2);//"hello world!"
90 _str.substring(2,-7);//he"
91 _str.substring(-2,-7);//" "
92 _str.substring(-7,7);//"hello w"
93 _str.substring(-7,-2);//" "
94 //slice,substr,substring只传入一个正整数,结果相同
95 //slice,substr,substring只传入一个负整数,slice,substr结果相同,这两个方法第一个参数为
96 //负会和长度求和
  • 数组操作

        数组操作的方法有:

            pop()、push()、shift()、unshift()、reverse()、sort()、concat()、slice()、splice()、indexOf()、lastIndexOf()、every()、filter()、forEach()、map()、some()、reduce()、reduceRight()

    

 1 var arr = [];
 2 /**
 3 *push,pop两个方法合用可以模拟栈结构(LIFO)
 4 *push()入栈,
 5 *pop()出栈
 6 */
 7 arr.push(1);//1
 8 arr.push(2);//2
 9 arr.pop();//2
10 arr.pop();//1
11 arr;//[]
12 /**
13 *push,shift两个方法合用可以模拟队列结构(FIFO)
14 *push()入队,
15 *shift()出队从头部移除数据并返回,刚好和pop()相反
16 */
17 arr.push(1);//1
18 arr.push(2);//2
19 arr.shift();//1
20 arr.shift();//2
21 arr;//[]
22 /**
23 *unshift()和shift()作用相反,unshift()在数组前面插入数据,而push()实在数据尾部添加数据
24 *unshift().push()返回Array的length
25 */
26 arr.unshif(1);
27 arr.unshift(2);
28 arr;//[2,1]
29 arr.shift();//2
30 arr.shift();//1
31 arr.push(1);//1
32 arr.push(2);//2
33 arr;//[1,2]
34 /**
35 *数组的排序有两个方法reverse()反序,sort()可传入排序方法,
36 *默认升序排序,排序过程中调用每项的toString()方法来确定顺序
37 */
38 arr.push('a',{x:2,y:3,toString:function(){return this.x;}},'b');
39 arr;//[1, 2, "a", Object, "b"]
40 arr.sort();//[1, 2, Object, "a", "b"]
41 arr.push(3);
42 arr.sort();//[1, 2, Object, 3, "a", "b"]  object在2和3之间,因为与比较时会调用toString()方法返回2
43 arr.reverse();//["b", "a", 3, Object, 2, 1]
44 //sort实现反序
45 arr.sort(function(va1,va2){if(va1<va2){return 1} else if(va1>va2){return -1}else{return 0}});//[1, 2, Object, 3, "a", "b"]
46 //concat合并数组,与String.prototype.concat作用相同
47 arr = [1,2,3];
48 arr.concat(['a','b']);//[1,2,3,'a','b'] 也可以arr.concat('a','b')
49 arr;//[1,2,3]不改变原数组
50 /**
51 *slice()它能够基于当前数组中的一或多个项创建一个新数组。 slice()方法可以
52 *接受一或两个参数,即要返回项的起始和结束位置。在只有一个参数的情况下, slice()方法返回从该
53 *参数指定位置开始到当前数组末尾的所有项。如果有两个参数,该方法返回起始和结束位置之间的项—
54 *—但不包括结束位置的项,不影响源数组
55 *也可以将类数组转换数组方法[].slice.call(类数组)
56 *常见的类数组有arguments,NodeList,styleSheets,HTMLCollection,HTMLFormControlsCollection
57 *HTMLOptionsCollection
58 */
59 arr.slice(-1);//[3]
60 arr.slice(0,2);[1,2]
61 arr.push(4);
62 arr.slice(0,-1);//[1,2,3]
63 /**
64 *splice()功能强大
65 *1.传入两个参数,分别位置和要删除的项数。第二参数为负取0,不存在取数组长度
66 *2.还可传多个参数表示插入和替换
67 */
68 arr = [1,2,3,4];
69 arr.splice(1);//[2,3,4]
70 arr = [1,2,3,4];
71 arr.splice(1,2);//[2,3]
72 arr = [1,2,3,4];
73 arr.splice(-1,2);//[4]
74 arr = [1,2,3,4];
75 arr.splice(-1,-2);//[]
76 arr.splice(1,0,9,9,9);//[1, 9, 9, 9, 2, 3, 4]在指定位置前插入
77 arr = [1,2,3,4];
78 arr.splice(1,2,9,9,9);//[1, 9, 9, 9, 4]替换

 字符串和数组很多方法用法类似。单独拿出便于对比记忆。

原文地址:https://www.cnblogs.com/jcheng996/p/5401088.html