06-字符串
06-字符串
屬性 截取字符串的長度str.length
方法:
charAt() 方法可返回指定位置的字符
concat() 方法用于連接兩個或多個字符串
indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。區分大小寫
//indexOf(查找的值,開始的位置)
lastIndexOf() 方法可返回一個指定的字符串值最后出現的位置
includes() 方法用于判斷字符串是否包含指定的子字符串 返回布爾型 true false
replace() 方法用于在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串
//replace(searchValue,newValue) 返回的是新的字符串
split() 方法用于把一個字符串分割成字符串數組 見js文件
substr() 方法可在字符串中抽取從開始下標開始的指定數目的字符
//substr(start,length)
substring() 方法用于提取字符串中介于兩個指定下標之間的字符
//substring(from,to)
slice(start, end) 方法可提取字符串的某個部分,并以新的字符串返回被提取的部分
substring和slice的區別見js文件
toLowerCase() 方法用于把字符串轉換為小寫
toUpperCase() 方法用于把字符串轉換為大寫
trim() 方法用于刪除字符串的頭尾空格
js文件:
var str = 'hello wrold'; var str1 = 'monkey '; //屬性 截取字符串的長度document.write(str.length); //11 //charAt() 方法可返回指定位置的字符document.write(str.charAt(1)); //edocument.write(str.charAt(str.length-1)); //d 獲取最后一個字符 //concat() 方法用于連接兩個或多個字符串var s = str1.concat(str,' welcome'); //monkey hello world welcome //indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。區分大小寫 document.write(str.indexOf('o')); //4 匹配成功后返回索引值document.write(str.indexOf('a')); //-1 沒有匹配成功則返回-1document.write(str.indexOf('o',5)); //8 indexOf(查找的值,開始的位置) //lastIndexOf() 方法可返回一個指定的字符串值最后出現的位置document.write(str.lastIndexOf('o')); //8 document.write(str.lastIndexOf('o',5)); //4 //replace() 方法用于在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串 //replace(searchValue,newValue) 返回的是新的字符串var s = str.replace('hello','hi,'); //hi,world //split() 方法用于把一個字符串分割成字符串數組var str3 = 'how,are,you';document.write(str3.split(",")); // ["how", "are", "you"]document.write(str3.split(",",2)); // ["how", "are"] 2表示返回數組的最大長度 //substr() 方法可在字符串中抽取從開始下標開始的指定數目的字符document.write(str.substr(4)); //o wrolddocument.write(str.substr(2,4));//substr(start,length) "llo " //substring() 方法用于提取字符串中介于兩個指定下標之間的字符 document.write(str.substring(4)); //o wrolddocument.write(str.substring(2,4)); //substr(from,to) ll 不包括to //slice(start, end) 方法可提取字符串的某個部分,并以新的字符串返回被提取的部分document.write(str.slice(2,4)); //lldocument.write(str.slice(-1)); //d -1表示最后一個字符串document.write(str.substring(-1)); //-1 表示0 hello world //slice()和substring()區別 思考題 /* var str="abcdefghijkl";console.log(str.slice(3,-4)); //defghconsole.log(str.substring(3,-4)); //abc*/ //toLowerCase() 方法用于把字符串轉換為小寫 //toUpperCase() 方法用于把字符串轉換為大寫 //trim() 方法用于刪除字符串的頭尾空格var str5 = ' hello ';document.write(str5.trim()); //hello總結