用正則實(shí)現(xiàn)一個(gè)trim函數(shù)(去除字符串的首尾空格)
// 去除空格
const trim_1 = (string) => string.replace(/^\s*|\s*$/g, '')
// 提取非空格
const trim_2 = (string) => string.replace(/^\s*(.*?)\s*$/g, '$1')
console.log(trim_1(' 1 2 3 4 ')) // '1 2 3 4'
console.log(trim_2(' 1 2 3 4 ')) // '1 2 3 4'
將字符串(多單詞)首字母轉(zhuǎn)化為大寫(xiě)末贾,剩下為小寫(xiě)
const transfrom_cap = (string) => {
return string.toLowerCase().replace(/(?:^|\s+)\w/g, (match) => match.toUpperCase())
}
console.log(transfrom_cap('hello world')) // 'Hello Word'
檢測(cè)URL是否為https或http開(kāi)頭
const reg_1 = /^https?:\/\//;
console.log(reg_1.test('https://www.baidu.com')) // true
console.log(reg_1.test('http://192.168.0.2')) // true
console.log(reg_1.test('http:s')) // false
console.log(reg_1.test('//s')) // false
檢測(cè)字符串str是否是都由中文組成
const reg_1 = /^[\u4E00-\u9FA5]+$/;
console.log(reg_1.test('葉問(wèn)')) // true
console.log(reg_1.test('葉問(wèn)2')) // false
console.log(reg_1.test('葉問(wèn) 三')) // false
數(shù)字千分位分割
const transfrom_ths = (arg) => String(arg).replace(/(?!^)(?=(\d{3})+$)/g, ',')
console.log(transfrom_ths('63001540')) // 63,001,540
console.log(transfrom_ths(112511311)) // 112,511,311
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者