(四)

作者: xpwei | 来源:发表于2018-03-28 20:48 被阅读3次

    Number类型
    toFixed()方法会按照指定的小数位返回数值的字符串:

    var num = 10;
    alert(num.toFixed(2)); //"10.00"
    

    toFixed()方法可以表示带有0到20个小数位的数值。但这只是标准实现的范围,有些浏览器也可能
    用于格式化数值的方法是toExponential(),该方法返回以指数表示法(也称为e表示法)表示的数值的字符串形式。与toFixed()一样,toExponential()也接收一个参数,而且该参数同样也是指定输出结果中的小数位数:

    var num = 10;
    alert(num.toExponential(1)); //"1.0e+1"
    

    对于一个数值来说,toPrecision()方法可能会返回固定大小(fixed)格式,也可能返回指数格式;具体规则是看哪种格式最合适。这个方法接受一个参数,即表示数值的所有数字的位数(不包括指数部分):

    var num = 99;
    alert(num.toPrecision(1)); //"1e+2"
    alert(num.toPrecision(2)); //"99"
    aler t(num.toPrecision(3)); //"99.0"
    

    String类型
    1、两个用于访问字符串中特定字符的方法是:charAt()和charCodeAt()。charAt()方法以单字符字符串的形式返回给定位置的那个字符:

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

    如果你想得到的不是字符而是字符编码,就使用charCodeAt():

    var stringValue = "hello world";
    alert(stringValue.charCodeAt(1)); //􀹼􀘜"101"
    

    ES5中还定义了另一个访问个别字符的方法。在支持此方法的浏览器中,可以使用这种方式访问:

    var stringValue = "hello world";
    alert(stringValue[1]); //"e"
    

    使用方括号表示法访问个别字符的语法得到了IE8及Firefox、Safari、Chrome和Opera所有版本的支持。如果是在IE7及更早版本中使用这种语法,会返回undefined值。

    2、字符串操作方法
    concat():用于将一或多个字符串拼接起来,返回拼接得到的新字符串:

    var stringValue = "hello ";
    var result = stringValue.concat("world");
    alert(result); //"hello world"
    alert(stringValue); //"hello"
    
    var stringValue = "hello ";
    var result = stringValue.concat("world", "!");
    alert(result); //"hello world!"
    alert(stringValue); //"hello"
    

    虽然concat()是专门用来拼接字符串的方法,但实践中使用更多的还是加号操作符(+)。而且,使用加号操作符在大多数情况下都比使用concat()方法要简便易行(特别是在拼接多个字符串的情况下)。
    ES还提供了三个基于子字符串创建新字符串的方法:slice()、substr()和substring()。这三个方法都会返回被操作字符串的一个子字符串,而且也都接受一或两个参数。第一个参数指定子字符串的开始位置,第二个参数(在指定的情况下)表示子字符串到哪里结束。具体来说,slice()和substring()的第二个参数指定的是子字符串最后一个字符后面的位置。而substr()的第二个参数指定的则是返回的字符个数。如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。与concat()方法一样,slice()、substr()和substring()也不会修改字符串本身的值——它们只是返回一个基本类型的字符串,对原始字符串没有任何影响:

    var stringValue = "hello world";
    alert(stringValue.slice(3)); //"lo world"
    alert(stringValue.substring(3)); //"lo world"
    alert(stringValue.substr(3)); //"lo world"
    alert(stringValue.slice(3, 7)); //"lo w"
    alert(stringValue.substring(3,7)); //"lo w"
    alert(stringValue.substr(3, 7)); //"lo worl"
    

    在传递给这些方法的参数是负值的情况下,它们的行为就不尽相同了。其中,slice()方法会将传入的负值与字符串的长度相加,substr()方法将负的第一个参数加上字符串的长度,而将负的第二个参数转换为0。最后,substring()方法会把所有负值参数都转换为0:

    var stringValue = "hello world";
    alert(stringValue.slice(-3)); //"rld"
    alert(stringValue.substring(-3)); //"hello world"
    alert(stringValue.substr(-3)); //"rld"
    alert(stringValue.slice(3, -4)); //"lo w"
    alert(stringValue.substring(3, -4)); //"hel"
    alert(stringValue.substr(3, -4)); //""􀇄􀩣􁌴􀞙􀘲􀇅
    

    3、字符串位置方法
    有两个可以从字符串中查找子字符串的方法:indexof()和lastIndexOf()。

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

    这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。
    4、trim()方法
    ES5为所有字符串定义了trim()方法。这个方法会创建一个字符串的副本,删除前置及后缀的所有空格。

    var stringValue = " hello world ";
    var trimmedStringValue = stringValue.trim();
    alert(stringValue); //" hello world "
    alert(trimmedStringValue); //"hello world"
    

    5、字符串大小写转换 方法

    var stringValue = "hello world";
    alert(stringValue.toLocaleUpperCase()); //"HELLO WORLD"
    alert(stringValue.toUpperCase()); //"HELLO WORLD"
    alert(stringValue.toLocaleLowerCase()); //"hello world"
    alert(stringValue.toLowerCase()); //"hello world"
    

    一般来说,在不知道自己的代码将在哪种语言环境中运行的情况下,还是使用针对地区的方法更稳妥一些。
    6、字符串的模式匹配方法
    String类型定义了几个用于在字符串中匹配模式的方法。第一个方法就是match(),在字符串上调用这个方法,本质上与调用RegExp的exec()方法相同。match()方法只接受一个参数,要么是一个正则表达式,要么是一个RegExp对象:

    var text = "cat, bat, sat, fat";
    var pattern = /.at/;
    //􁇑 pattern.exec(text)􁁎􀽞
    var matches = text.match(pattern);
    alert(matches.index); //0
    alert(matches[0]); //"cat"
    alert(pattern.lastIndex); //0
    

    另一个用于查找模式的方法是search()。这个方法的唯一参数与match()方法的参数相同:由字符串或RegExp对象指定的一个正则表达式。search()方法返回字符串中第一个匹配项的索引;如果没有找到匹配项,则返回-1。而且,search()方法始终是从字符串开头向后查找模式:

    var text = "cat, bat, sat, fat";
    var pos = text.search(/at/);
    aler t(pos); //1
    

    为了简化替换字符串的操作,ES提供了replace()方法。这个方法接受两个参数:第一个参数可以是一个RegExp对象或者一个字符串(这个字符串不会被转换成正则表达式),第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串,那么只会替换第一个子字符串。要想替换所有子字符串,唯一的办法就是提供一个正则表达式,而且要指定全局(g)标志:

    var text = "cat, bat, sat, fat";
    var result = text.replace("at", "ond");
    alert(result); //"cond, bat, sat, fat"
    result = text.replace(/at/g, "ond");
    aler t(result); //"cond, bond, sond, fond"
    
    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;";
            }
        });
    }
    alert(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
        //&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;
    

    最后一个与模式匹配有关的方法是split(),这个方法可以基于指定的分隔符将一个字符串分隔成多个子字符串,并将结果放在一个数组中。分隔符可以是字符串,也可以是一个RegExp对象(这个方法不会将字符串看成正则表达式)。split()方法可以接受可选的第二个参数,用于指定数组的大小,以确保返回的数组不会超过既定大小:

    var colorText = "red,blue,green,yellow";
    var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
    var colors2 = colorText.split(",", 2); //["red", "blue"]
    var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
    

    对split()中正则表达式的支持因浏览器而异。尽管对于简单的模式没有什么区别,但对于未发现匹配项以及带有捕获组的模式,匹配的行为就大不相同了:

    • IE8及之前版本会忽略捕获组。ECMA-262规定应该把捕获组拼接到结果数组中。IE9能正确地在结果中包含捕获组。
    • Firefox3.6及之前版本在捕获组未找到匹配项时,会在结果数组中包含空字符串;ECMA-262规定没有匹配项的捕获组在结果数组中应该用undefined表示。

    在正则表达式中使用捕获组时还有其他微妙的差别。在使用这种正则表达式时,一定要在各种浏览器下多做一些测试。
    7、localeCompare()方法
    与操作字符串有关的最后一个方法是localeCompare(),这个方法比较两个字符串,并返回下列值中的一个:

    • 如果字符串在字母表中应该排在字符串参数之前,则返回一个负数(大多数情况下是-1,具体的值要视实现而定)。
    • 如果字符串等于字符串参数,则返回0;
    • 如果字符串在字母表中应该排在字符串参数之后,则返回一个正数(大多数情况下是1.。。。)
    var stringValue = "yellow";
    alert(stringValue.localeCompare("brick")); //1
    alert(stringValue.localeCompare("yellow")); //0
    alert(stringValue.localeCompare("zoo")); //-1
    

    因为localeCompare()返回的数值取决于实现,所以最好是像下面例子所示的这样使用这个方法:

    function determineOrder(value) {
        var result = stringValue.localeCompare(value);
        if (result < 0){
            alert("The string 'yellow' comes before the string '" + value + "'.");
        } else if (result > 0) {
            alert("The string 'yellow' comes after the string '" + value + "'.");
        } else {
            alert("The string 'yellow' is equal to the string '" + value + "'.");
        }
    }
    determineOrder("brick");
    determineOrder("yellow");
    determineOrder("zoo");
    

    8、fromCharCode()方法
    String构造函数本身还有一个静态方法:fromCharCode()。这个方法的任务是接收一或多个字符编码,然后将它们转换成一个字符串。从本质上来看,这个方法与实例方法charCodeAt()执行的是相反的操作:

    alert(String.fromCharCode(104, 101, 108, 108, 111)); //"hello"
    

    相关文章

      网友评论

          本文标题:(四)

          本文链接:https://www.haomeiwen.com/subject/dhmscftx.html