之前都是上网看影片学Javascript
常常遇到.push(), .split(), .join(), .slice(), splice()...等等字串或阵列处理後面串一堆函式
直接先崩溃一波,这次到职训局打算把基础打好(现在基础打好一点,上班才不会被电)
以下整理了处理字串的函式
把英文字母全部转大写
const text = 'Hello World!!'
text = text.toUpperCase()
console.log(text) // HELLO WORLD!!
把英文字母全部转小写
const text = 'Hello World!!'
text = text.toLowerCase()
console.log(text) // hello world!!
回传整数
const text = '1234.678'
const num = parseInt(text)
console.log(num) // 1234
若把非数字的字串转成整数时会回传NaN
const text = 'abcd'
const num = parseInt(text)
console.log(num) // NaN
回传浮点数
const text = '1234.678'
const num = parseFloat(text)
console.log(num) // 1234.678
跟.parseInt()一样回传NaN
const text = 'abcd'
const num = parseFloat(text)
console.log(num) // NaN
这个函式很常使用,可以用在请使用者输入input 将字串的头尾删除或处理资料时前後有空白的时候
const text = ' Hello World!! '
text = text.trim()
console.log(text) // Hello World!!
回传true,这代表此字串中有 H
const text = 'Hello World!!'
text = text.includes('H')
console.log(text) // true
回传false,这代表此字串中没有 z
const text = 'Hello World!!'
text = text.includes('z')
console.log(text) // false
里面有三个 l 但只回传第一个位置 2
const text = 'Hello World!!'
const idx = text.indexOf('l')
console.log(idx) // 2
因为字串内没有 z 所以回传 -1
这可以来检验处理的资料里面是否有特定的字串
const text = 'Hello World!!'
const idx = text.indexOf('z')
console.log(idx) // -1
从位置1取长度3个字串
const text = 'ABCDEFG'
const substr = text.substr(1, 3)
console.log(substr) // BCD
如果不给长度则取後最後一个字串
const text = 'ABCDEFG'
const substr = text.substr(1)
console.log(substr) // BCDEFG
从位置1取到位置3但不包含第3个字
const text = 'ABCDEFG'
const substring = text.substring(1, 3)
console.log(substring) // BC
跟.substr() 一样不加入第二个变数则直接取到最後一个
const text = 'ABCDEFG'
const substring = text.substring(1)
console.log(substring) // BCDEFG
从位置1取到位置5但不包含第5个字(怎麽感觉跟.substring()很像)
改负数看看
const text = 'ABCDEFG'
const slice = text.slice(1, 5)
console.log(slice) // BCDE
从位置1(A)取到位置 -3 (往回数3个EFG)个但不包含第 -3 个字
两个都改成负数试看看
const text = 'ABCDEFG'
const slice = text.slice(1, -3)
console.log(slice) // BCD
从位置 -4 (D)取到位置 -2 (往回数2个FG)个但不包含第 -2 个字
const text = 'ABCDEFG'
const slice = text.slice(-4, -2)
console.log(slice) // DE
如果变数改成text.slice(-1, -2)会找不到东西
const text = 'ABCDEFG'
const slice = text.slice(-1, -2)
console.log(slice) // ''
把逗号切掉并回传成阵列
const text = '1,2,3,4,5,6,7,8'
let split = text.split(',')
console.log(split) // ['1', '2', '3', '4', '5', '6', '7', '8']
字串处理的函式大概先到这边,想到其他的话再补充
<<: Day 32 - 透过手机呼叫 Amazon API Gateway 上传图片到 S3
同样是Word项目符号,为什麽别人添加的总是那麽好看,还可以自己定义log图标?这是因为别人善於利用...
哈罗,我是Eason,欢迎来到我的 「WordPress 再进化,用 Next.js 拆分前端,实现...
Elasticsearch在Uber的Marketplace Dynamics核心数据系统中扮演着关...
CORS 全称 Cross-Origin Resource Sharing, 中文为「跨来源资源共用...
蛤?重建 VPC? 干嘛不调整好现有的架构就好了? AWS 官方文件有提到, 官方预设都是 172....