首页 / 操作系统 / Linux / JavaScript类型系统之String
前面的话 string是由单引号或双引号括起来的字符序列,且被限定在同种引号之间,即必须是成对单引号或双引号。字符串的独特在于它是唯一没有固定大小的原始类型 字符串中每个字符都有特定的位置,首字符从位置0开始,第二个字符在位置1,依次类推,这意味着字符串中的最后一个字符的位置一定是字符串的长度减1特点 JavaScript中的字符串是不可变的。字符串连接需要先创建一个新字符串,然后在新字符串中填充两个需要拼接的字符串,最后再销毁原来的字符串。这个过程在后台发生,也是在某些旧版本浏览器(IE6)拼接字符串速度慢的原因,但后来已经解决了这个低效率问题。var lang = "java"; lang = lang + "script";转义字符 转义字符也叫字符字面量 空字节
换行 制表 空格
回车 f 进纸 \ 斜杠 " 单引号 " 双引号 xnn 以十六进制nn表示一个字符(n为0-f),如x41表示"A" unnnn 以十六进制nnnn表示一个Unicode字符(n为0-f),如u03a3表示希腊字符ε 当字符串中包含引号,有三种解决方案 [1]单引号中嵌入双引号 [2]双引号中嵌入单引号 [3]使用转义符""console.log(""test"");//"test" console.log(""test"");//"test" console.log(""test"");//"test"继承的方法 String类型是与字符串对应的包装类型,继承了引用类型的通用方法 valueOf()、toString()和toLocaleString():返回字符串表示console.log("test".valueOf());//"test" console.log("test".toString());//"test" console.log("test".toLocaleString());//"test"length属性 String类型的每个实例都有一个length属性,表示字符的个数 [注意]该属性只可读取,不可改变var str = "test"; console.log(str.length);//4 str.length = 6; console.log(str,str.length);//"test",4String()方法 String()方法的转换规则是: [1]如果值有toString()方法,则调用该方法(没有参数)并返回相应结果 [2]null和undefined没有toString()方法,则返回null和undefinedconsole.log(undefined.toString())//报错 console.log(null.toString())//报错 console.log(String(undefined));//"undefined" console.log(String(null));//"null" console.log(String(true),String(false));//"true" "false" console.log(String(10.1));//10.1 console.log(String({}));//[object Ojbect] [注意]要把某个值转换为字符串,可以使用加号操作符把它与一个空字符串""加在一起console.log(typeof (1 + ""),(1 + ""));//string "1" console.log(typeof (undefined + ""),(undefined + ""));//string "undefined" console.log(typeof (null + ""),(null + ""));//string "null" console.log(typeof (true + ""),(true + ""));//string "true" console.log(typeof ({} + ""),({} + ""));//string "[object Object]"访问字符方法 接收一个基于0的字符位置的参数,并以单字符字符串的形式返回charAt():返回给定位置的字符 [注意]当参数为空时,默认参数为0;当参数超出范围时,则什么都不输出var str = "hello"; console.log(str.charAt(1));//e console.log(str.charAt(-1));//空 console.log(str.charAt(10));//空 console.log(str.charAt());//h中括号加数字索引(ES5):返回给定位置的字符(IE7-不支持,输出undefined) [注意]当参数超出范围时,输出undefined;当参数为空时,报错var str = "hello"; console.log(str[1]);//e console.log(str[-1]);//undefined console.log(str[10]);//undefined console.log(str[]);//报错charCodeAt():返回给定位置的字符编码,字符编码为Number类型 [注意]当参数为空时,默认参数为0;当参数超出范围时,则输出NaNvar str = "hello"; console.log(str.charCodeAt(1));//101 console.log(str.charCodeAt(-1));//NaN console.log(str.charCodeAt(10));//NaN console.log(str.charCodeAt());//104String.fromCharCode():把一个或多个编码值转成一个字符串(静态方法) [注意]参数范围为ASCII表的范围 var stringValue = "hello"; console.log(stringValue.charAt(1));//"e" console.log(stringValue.charCodeAt(1));//101 console.log(typeof stringValue.charCodeAt(1));//"number" console.log(String.fromCharCode(104,101,108,108,111));//"hello" console.log(String.fromCharCode(0x6211,0x662f,0x5c0f,0x706b,0x67f4));//"我是小火柴" console.log(stringValue[1]);//"e"字符串拼接 concat():可以接受任意多个参数,用于将一个或多个字符串拼接起来,返回拼接得到的新字符串+:加号操作符在多数情况下比concat()更简便var stringValue = "hello "; console.log(stringValue.concat("world","!"));//"hello world!" console.log(stringValue + "world" + "!");//"hello world!"创建字符串 返回被操作字符串的一个子字符串,若无参数则返回原字符串。共substr、subtring和slice三种substr(a,b):a->子字符串开始位置、b->子字符串长度(可选,默认到原字符串结束) 设原字符串长度为len [1]当a>=len时,不输出 [2]当 a<0 且 |a|<len 时,从后往前数,输出|a|个字符 [3]当 a<0 且 |a|>= len 时,输出从(0)到(b)的位置 [4]当 b<0 时,b = 0 [5]当 b>= 可提供字符数时,以最大字符数输出 [注意]IE8-在处理第一个参数为负值时存在问题,输出原字符串var stringValue = "hello world"; console.log(stringValue.substr());//"hello world" console.log(stringValue.substr(2));//"llo world" console.log(stringValue.substr(20));//空 console.log(stringValue.substr(-2,3));//"ld" console.log(stringValue.substr(-2,20));//"ld" console.log(stringValue.substr(-20,2));//"he" console.log(stringValue.substr(-20,-2));//空 console.log(stringValue.substr(2,5));//llo wsubstring(a,b):a->子字符串开始位置、b->子字符串结束后一位的位置(可选,默认为原字符串长度) 设原字符串长度为len [1]当a<0时,a=0;当b<0时,b=0 [2]当a>b>0时,substring(b,a) [3]当a>=len时,无输出 [4]当b>=len时,以最大字符数输出var stringValue = "hello world"; console.log(stringValue.substring());//"hello world" console.log(stringValue.substring(2));//"llo world" console.log(stringValue.substring(20));//空 console.log(stringValue.substring(-2,2));//"he" console.log(stringValue.substring(-2,20));//"hello world" console.log(stringValue.substring(3,2));//"l" console.log(stringValue.substring(-20,2));//"he" console.log(stringValue.substring(-20,-2));//空 slice(a,b):a->子字符串开始位置,b->子字符串结束后一位的位置(可选,默认为原字符串长度) 设原字符串长度为len [1]当 a>=len 时,不输出 [2]当 a<0 且 |a|<len 时,a = len - |a| [3]当 a<0 且 |a|>= len 时,输出从(0)到(b)的位置 [4]当 b>=len 时,相当于没有b [5]当 b<0 且 |b|<len 时,b = len - |b| [6]当 b<0 且 |b|>=len 时,不输出 [7]当 a>b>0时,不输出var stringValue = "hello world"; console.log(stringValue.slice());//"hello world" console.log(stringValue.slice(2));//"llo world" console.log(stringValue.slice(2,-5));//"ll0" console.log(stringValue.slice(2,-20));//空 console.log(stringValue.slice(20));//空 console.log(stringValue.slice(-2,2));//空 console.log(stringValue.slice(-2,-20));//空 console.log(stringValue.slice(-2,20));//"ld" console.log(stringValue.slice(-20,2));//"he" console.log(stringValue.slice(-20,-2));//"hello wor"字符串位置 有两个从字符串中查找子字符串的方法indexOf()和lastIndexOf()。这两个方法都接受两个参数:要查找的子字符串和表示查找起点位置的索引(可选)。返回第一个满足条件的子字符串在字符串中的位置,若没有找到则返回-1(位置方法不会影响原字符串) [注意]返回值是Number类型indexOf():从左到右搜索lastIndexOf():从右到左搜索var string = "hello world world"; console.log(string.indexOf("ld",10));//15 console.log(string.lastIndexOf("ld",10));//9[tips]查找出字符串所有符合条件的子字符串function allIndexOf(str,value){ var result = []; var pos = str.indexOf(value); while(pos > -1){ result.push(pos); pos = str.indexOf(value,pos+value.length); } return result; } console.log(allIndexOf("helllhelllhelll","ll"));//[2,7,12]大小写转换 toUpperCase():全部转换成大写toLowerCase():全部转换成小写toLocaleUpperCase():全部转换成大写(针对地区)toLocaleLowerCase():全部转换成小写(针对地区) [注意]在不知道自己的代码将在哪个语言环境中运行的情况下,使用针对地区的方法更稳妥var string = "Hello World"; console.log(string.toLowerCase());//hello world console.log(string.toLocaleLowerCase());//hello world console.log(string.toUpperCase());//HELLO WORLD console.log(string.toLocaleUpperCase());//HELLO WORLD [注意]大小写转换方法可以连续使用console.log((string.toUpperCase()).toLowerCase());//hello world字符串比较 localeCompare():用于比较两个字符串,如果字符串在字母表中应该排在字符串参数之前,则返回一个负数(大多数情况下为-1);如果字符串等于字符串参数,则返回0;如果在之后,则返回一个正数(大多数情况下为1) [注意]在ASCII表中,大写字母排在小写字母前面var stringValue = "yellow"; console.log(stringValue.localeCompare("brick"));//1 "y"> "b" console.log(stringValue.localeCompare("yellow"));//0 "yellow" == "yellow" console.log(stringValue.localeCompare("zoo"));//-1 "yellow" < "zoo"模式匹配 String类型定义了几个用于字符串匹配模式的方法。模式匹配涉及到正则表达式的内容,详细信息移步至此match() 只接受一个参数,正则或字符串,把匹配的内容保存到一个数组中返回 [注意]加上全局标记时,match()方法返回值中没有index和input属性[1]不加/gvar string = "cat,bat,sat,fat"; var pattern = /.at/; var matches = string.match(pattern); console.log(matches,matches.index,matches.input);//["cat"] 0 "cat,bat,sat,fat"[2]加/gvar string = "cat,bat,sat,fat"; var pattern = /.at/g; var matches = string.match(pattern); console.log(matches,matches.index,matches.input);//["cat","bat","sat","fat"] undefined undefined[3]字符串var string = "cat,bat,sat,fat"; var pattern = "at"; var matches = string.match(pattern); console.log(matches,matches.index,matches.input);//["at"] 1 "cat,bat,sat,fat"search() 只接受一个参数,正则或字符串,返回匹配的内容在字符串中首次出现的位置,类似于不能设置起始位置的indexOf,找不到返回-1[1]正则(加/g和不加/g效果一样)var string = "cat,bat,sat,fat"; var pattern = /.at/; var pos = string.search(pattern); console.log(pos);//0[2]字符串var string = "cat,bat,sat,fat"; var pattern = "at"; var pos = string.search(pattern); console.log(pos);//1[tips]找出匹配的所有位置function fnAllSearch(str,pattern){ var pos = str.search(pattern); var length = str.match(pattern)[0].length; var index = pos+length; var result = []; var last = index; result.push(pos); while(true){ str = str.substr(index); pos = str.search(pattern); if(pos === -1){ break; } length = str.match(pattern)[0].length; index = pos+length; result.push(last+pos); last += index; } return result; } console.log(fnAllSearch("cat23fbat246565sa3dftf44at",/d+/));//[3,9,17,22]replace() 该方法接收两个参数:第一个为正则表达式或字符串(待查找的内容)、第二个为字符串或函数(替换的内容)[1]字符串替换var string = "cat,bat,sat,fat"; var result = string.replace("at","ond"); console.log(result);//"cond,bat,sat,fat"[2]正则无/g替换var string = "cat,bat,sat,fat"; var result = string.replace(/at/,"ond"); console.log(result);//"cond,bat,sat,fat"[3]正则有/g替换var string = "cat,bat,sat,fat"; var result = string.replace(/at/g,"ond"); console.log(result);//"cond,bond,sond,fond"[4]函数替换 在只有一个匹配项(即与模式匹配的字符串的情况下,会向这个函数传递3个参数:模式的匹配项、模式匹配项在字符串中的位置、原始字符串。在正则表达式定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项、第二个捕获组的匹配项……第N个捕获组的匹配项,但最后两个参数仍然分别是模式的匹配项在字符串中的位置和原始字符串,这个函数返回一个字符串var string = "cat,bat,sat,fat"; var index = 0; var result = string.replace(/at/g,function(match,pos,originalText){ index++; if( index== 2){ return "wow"; }else{ return "0"; } }); console.log(result);//"c0,bwow,s0,f0"[tips]防止跨站脚本攻击xss(css)function htmlEscape(text){ return text.replace(/[<>"&]/g,function(match,pos,originalText){ switch(match){ case "<": return "<"; case ">": return ">"; case "&": return "&"; case """: return """; } }); } console.log(htmlEscape("<p class="greeting">Hello world!</p>")); //<p class=" greeting">Hello world!</p> console.log(htmlEscape("<p class="greeting">Hello world!</p>")); //同上split() 这个方法可以基于指定的分隔符将一个字符串分割成多个字符串,并将结果放在一个数组中,分隔符可以是字符串,也可以是一个RegExp。该方法可以接受第二个参数(可选)用于指定数组的大小,如果第二个参数为0-array.length范围内的值时按照指定参数输出,其他情况将所有结果都输出 [注意]IE8-对split()中的正则表达式,会忽略捕获组[tips]如果是split(""),则原来的数组会一个字符字符分割后传出来var colorText = "red,blue,green,yellow"; console.log(colorText.split(""));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"] console.log(colorText.split(","));//["red", "blue", "green", "yellow"] console.log(colorText.split(",",2));//["red", "blue"] console.log(colorText.split(/,/));//["red", "blue", "green", "yellow"] console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"] console.log(colorText.split(/[^,]+/));//将除去逗号以外的字符串变为分隔符["", ",", ",", ",", ""],IE8-会识别为[",",",",","]trim()(ECMAScript5) 返回删除前置及后缀空格的字符串副本var string = " hello world "; console.log(string.trim());//"hello world";[tips1]可以用trim()来判断输入的字符是否为空if(usename.trim().length){ alert("correct"); }else{ alert("error"); }[tips2]用正则模拟trim()function fnTrim(str){ return str.replace(/^s+|s+$/,"") } console.log(fnTrim(" hello world "));//"hello world"本文永久更新链接地址 :http://www.linuxidc.com/Linux/2016-01/127131.htm
收藏该网址