javascript类型系统之String

前面的话

  string是由单引号或双引号括起来的字符序列,且被限定在同种引号之间,即必须是成对单引号或双引号。字符串的独特在于它是唯一没有固定大小的原始类型

  字符串中每个字符都有特定的位置,首字符从位置0开始,第二个字符在位置1,依次类推,这意味着字符串中的最后一个字符的位置一定是字符串的长度减1

特点

  javascript中的字符串是不可变的。字符串连接需要先创建一个新字符串,然后在新字符串中填充两个需要拼接的字符串,最后再销毁原来的字符串。这个过程在后台发生,也是在某些旧版本浏览器(IE6)拼接字符串速度慢的原因,但后来已经解决了这个低效率问题

var lang = "java";
lang = lang + "script";

 

转义字符

  转义字符也叫字符字面量


\0 空字节
\n 换行
\t 制表
\b 空格
\r 回车
\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",4

 

String()方法

  String()方法的转换规则是:

  [1]如果值有toString()方法,则调用该方法(没有参数)并返回相应结果

  [2]null和undefined没有toString()方法,则返回null和undefined


console.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;当参数超出范围时,则输出NaN

var str = "hello";
console.log(str.charCodeAt(1));//101
console.log(str.charCodeAt(-1));//NaN
console.log(str.charCodeAt(10));//NaN
console.log(str.charCodeAt());//104

String.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 w

substring(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]不加/g

var 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]加/g

var 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 '&lt;';
            case '>':
            return '&gt;';
            case '&':
            return '&amp;';
            case '\"':
            return '&quot;';
        }
    });
}
console.log(htmlEscape('<p class=\"greeting\">Hello world!</p>'));
//&lt;p class=&quot; greeting&quot;&gt;Hello world!&lt;/p&gt;
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'

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值