字符串
类型判断
转换数字
const t = '5' // 字符串
const t_int = +t // 数字
const t = () => '5' // 字符串
const t_int = +t() // 数字
console.log(typeof +'5'); // number
slice - 截取、切片
- 截取
str = 'capsion'
// 截取到倒数第二位
// -1 代表最后一位
new_str = str.slice(0, -2)
字符串查找
常用方法 | 说明 |
---|---|
charAt() | 返回字符串中的第 n 个字符 |
charCodeAt() | 返回字符串中的第 n 个字符的代码 |
indexOf() | 检索字符串 |
lastIndexOf() | 从后向前检索一个字符串 |
match() | 找到一个或多个正则表达式的匹配 |
search() | 检索与正则表达式相匹配的子串 |
endsWith() | 检查字符串结尾 |
字符串替换
replace
// 匹配一个
let tag = ' '
const target = '我 需 要 替换 全部 空格'
const newStr = target.replace(tag, '')
// 只会替换第一个
// '我需 要 替换 全部 空格'
// 匹配多个
let tag = new RegExp(' ', "g")
const target = '我 需 要 替换 全部 空格'
const newStr = target.replace(tag, '')
// 使用正则可以替换多个
// '我需要替换全部空格'
重复一个字符串多次
//常规写法
let str = '';
for(let i = 0; i < 5; i ++) {
str += '美女方便给个微信么 ';
}
// 使用 repeat
'美女方便给个微信么'.repeat(5);