字符串

73 阅读1分钟

1.字符串的常用方法

// charAt() 根据指定的索引返回具体的字符
var str = 'hello world';
var result = str.charAt(1);
document.write(result); // e

// charCodeAt() charCodeAt返回的是字符对应的Unicode编码
var str = 'Frankenstein';
    var result = str.charCodeAt(3);
    var result1 = str.charCodeAt(23);
    console.log(result); // 110
    console.log(result1); // NaN

// toUpperCase()、toLowerCase()
// toUpperCase方法能够把字符串中的英文字母全都转换成大写字母。
// toLowerCase方法能够把字符串中的英文字母全都转换成小写字母。
var str = "heHELLO WORLD";
    var newStr = str.toUpperCase();
    var newStr1 = str.toLowerCase();
    console.log(newStr); //HEHELLO WORLD
    console.log(newStr1); //hehello world

// subString() 表示从fromIndex位置处开始截取,到toIndex位置结束之间的字符串,
//             不包含第二个参数的字符
var str = 'The Three FireGuners';
    var result = str.substring(4, 9);
    var result1 = str.substring(9, 4);  
    如出现第一个参数大于第二个参数的情况,subString()会自动变更两个参数的位置
    console.log(result); // Three
    console.log(result1); // Three

 // replace() replace方法能够将【查找到的第一个指定字符串】替换成【目标字符串】
 var str = 'hello sxt! gongbye sxt';
        var newStr = str.replace('sxt', 'xxx');
        console.log(newStr); //hello xxx! gongbye sxt
        console.log(str); //hello sxt! gongbye sxt

// split()  根据指定的符号对字符串进行分割,分割后的每一个子元素整合成一个数组返回
var str = 'hello sxt !goodbye sxt';
    console.log(str.split("")); // (22) ["h", "e", "l", "l", "o", " ", "s", "x",
    "t", " ", "!", "g", "o", "o", "d", "b", "y", "e", " ", "s", "x", "t"]
    console.log(str.split(' ')); // (4) ["hello", "sxt", "!goodbye", "sxt"]