js中字符串操作

来源:互联网 发布:linux free swap 编辑:程序博客网 时间:2024/06/04 19:19

js中字符串操作

一.String类型:

1.length:字符串长度

2.构造方法
new String("Hello World")
3.fromCharCode()
静态,接收一或多个字符编码转换成字符串
String.fromCharCode(104, 101, 108, 108, 111);// "hello"

二.常用函数:

测试使用的字符串:var stringValue = "Hello World";

1.charAt()

返回给定位置的字符,获取不到返回空字符串
参数范围:0-string.length-1
stringValue.charAt(0);// "c"stringValue.charAt(100);// "" 空串

2.charCodeAt()

返回给定位置字的符编码,获取不到返回NaN,可用isNaN()函数判断
参数范围:0-string.length-1
stringValue.charCodeAt(0);// 72isNaN(stringValue.charCodeAt(100));// true

3.concat()

将一个或多个字符串拼接起来
stringValue.concat("!", "!");// "Hello World!!"

4.substr()

返回子字符串
第一个参数:字符串开始位置
第二个参数(可选):返回字符个数
stringValue.substr(1);// "ello World"stringValue.substr(1, 1);// "e"

5.substring()

第一个参数:字符串开始位置
第二个参数(可选):子字符串最后一个字符后面的位置
stringValue.substring(1);// "ello World"stringValue.substring(1, 8);// "ello Wo"

6.slice()

正确参数时类似于substring()
第一个参数:字符串开始位置
第二个参数(可选):子字符串最后一个字符后面的位置

substr() substring() slice()比较
若传入负值
(1).slice()方法:将负值与字符串长度相加
(2).substr()方法:第一个参数为负:负值加上字符串的长度 第二参数为负:置为0
(3).substring()方法:负值都置为0,并将较小的参数作为开始、较大的参数作为结束
stringValue.substr(-3);// "rld"  -3+11=8stringValue.substring(3, -3);// "Hel"  (3, -3)->(3, 0)->(0, 3)stringValue.slice(-3, -3);// "" 空串 (-3, -3)->(8, 8)

7.indexOf()

查找给定的子字符串,未查找到返回-1,从前往后查找
stringValue.indexOf("a");// -1stringValue.indexOf("H");// 0

8.lastIndexOf()

同上,从后往前查找

9.trim()

删除前置以及后缀的所有空格

10.toLowerCase() toLocaleLowerCase() toUpperCase() toLocaleUpperCase()

stringValue.toLowerCase();// "hello world"stringValue.toUpperCase();// "HELLO WORLD"

11.match()

匹配字符串
参数:一个正则表达式或RegExp对象,返回匹配到的数组
var text = "cat,bat,sat,fat";var pattern = /.at/;var matches = text.match(pattern);console.log(matches);// ["at"]

12.search()

返回字符串中第一个匹配项的索引,未匹配到,返回-1,从前往后查找
参数:正则表达式或RegExp对象
var text = "cat,bat,sat,fat";text.search(/at/);// 1

13.replace()

替换匹配到的字符串
第一个参数:RegExp对象或字符串(不转换为正则) 若需全部替换,指定全局(g)标志
第二个参数:字符串或函数
var text = "cat,bat,sat,fat";console.log(text.replace("at", "ond"));// 字符串方式  ["cond", "bat", "sat", "fat"]console.log(text.replace(/at/g, "ond"));// 正则方式 全局,全部替换  ["cond", "bond", "sond", "fond"]

14.split()

基于指定的分隔符将字符串分割成多个子字符串,返回数组
 第一个参数:字符串或RegExp对象
 第二个参数(可选):指定数组的大小
var text = "cat,bat,sat,fat";console.log(text.split(","));// ["cat", "bat", "sat", "fat"]console.log(text.split(/,/));//  ["cat", "bat", "sat", "fat"]

15.localCompare()

比较两个字符串,大于返回正数(大多数为1),等于返回0,小于返回负数(多数为-1)
"abc".localeCompare("bcd");// -1"abc".localeCompare("abc");// 0"bcd".localeCompare("acd");// 1