es6新的字串方法
如何修改函式使得返回的時間永遠是兩個字元長度表示 03:03
//獲取當前的小時數和分鐘數
function
gettime()
console.log(gettime()) // 上午3時03分會返回 字串3:3
複製**
所有這些方法都是區分大小的,執行搜尋前要將字串小寫化
所有這些方法還可以指定第二個引數指定字串中的起始搜尋位置startswith()
下面我們來看兩個案例
現在有了es6的/*
1.來自不同廠家的產品資料,**欄位有的有美元符,沒有的需要我們自己加上,
所以需要檢查是否已存在$的字段
*/const product_arr=[,,
,]for(let i of product_arr)else}/*
2。根據使用者的當前**判斷所在區
*/let usertel='021-888-8880';
const area_code= '021'
if(usertel.substr(0,3)===area_code)
複製**
startswith()
,我們可以改寫如下:我們一眼就能看出他在做什麼。
endswith()、includes()if(i.price.starstwith('$'))
if(usertel.starstwith(area_code))
複製**
let name='east-boat';
console.log(name.startswith('east')); //true
console.log(name.endswith('boat')); //true
console.log(name.includes('t-b')); //true
console.log(name.includes('-bo')); //true
複製**
要求某個函式接受用十進位制(基數為10)表示的ip位址,將其轉化為二進位制(基數為2)表示
但是當ip位址小於128的數時,二進位制數小於8位數字,此時上面的函式是無法執行的function
binaryip(decimalipstr)).join('.')
}console.log(binaryip('192.168.2.1'));
複製**
解決辦法:需要用0填充每乙個位元組,知道每乙個都是8位
string.prototype.repeat
'0'.repeat(8) // 呼叫8次 '00000000'
'0'.repeat(4.9) // 如果不是整數,向下取整而不是四捨五入 '0000'
複製**
string.prototype.padstart和 string.prototype.padend// 新增es6特性解決
function
binaryip(decimalipstr)).join('.')
}console.log(binaryip('192.168.2.1'));
複製**
console.log('abc'.padstart(4)); //缺省會在開頭新增三個空格
console.log('abc'.padstart(4).split('')); [ ' ','a', 'b', 'c']
console.log('abc'.padend(4)); //缺省會在結尾新增個空格
console.log('abc'.padend(4).split('')); [ 'a', 'b', 'c', ' ' ]
//設定返回的字串最大長度和所填充的字串
console.log('123'.padstart(6,'x')); //***123
console.log('123'.padstart(6,'xy'));//xyx123
console.log('123'.padstart(6,'xyz'));//xyz123
console.log('123'.padend(6,'x')); //123***
console.log('123'.padend(6,'xy'));//123xyx
console.log('123'.padend(6,'xyz'));//123xyz
console.log('123'.padend(2,'x')); //如果最大長度小於原始字串的長度,那麼原始字串不會被擷取,直接返回,不作任何填充
複製**
使用上面的方法重新binaryip
方法
function
binaryip(decimalipstr)).join('.')
}console.log(binaryip('192.168.2.1'));
複製**
//使用repeat來寫乙個函式,重複任何字串到50個字元,截斷任何多餘的字元
function
repeat50(str)
console.log(repeat50('east-boat'));
//east-boateast-boateast-boateast-boateast-boateast-
複製**
ES6 函式與物件,新字串
1 函式預設引數 function sum a,b return a b sum 1 值為1,此時預設b的值為0 sum 1,2 值為3,當a和b都賦值時,就不取他們的預設值b b 0 一句話等價於 if b else上面的形式也可以直接寫成 function sum a 0,b 0 sum 引數1...
es6 新增字串方法
es6新增了4個字串處理的方法 startswith,endswith,includes,repeat。let str lxy 字串是否以某個字元開頭 console.log str.startswith l true console.log str.startswith x false 字串是否以...
ES6字串方法
es6 新提出一些字串方法方便使用 查詢子字串 string.includes 查詢字串是否包含某子字串 string.startswith 查詢字串開始處是否包含某子字串 string.endswith 查詢字串結束處是否包含某子字串 上述方法均返回boolean值,第乙個引數為所需查詢的子字串,...