JS 之 操作 String 字符串

目录

String - JavaScript | MDN

一. 访问字符串字符

二. 字符串遍历

1 -  普通循环

2 - for...of循环

三. 修改字符串

四. toUpperCase : 将所有字符变为大写

五. toLowerCase : 将所有字符变为小写

六. 查找字符串

1 - indexOf ( searchString , fromIndex ) : 查找

2 - includes( searchString , position ) : 查找

3 - startsWith : 以xxx开头

4 - endsWith : 以xxx结尾

七. 替换字符串

1 - replace : 替换找到的第一个

2 - replaceAll : 替换找到的所有

八. 获取子字符串 

九. 拼接字符串

1 - + 

2 - concat

十. trim

1. trim : 删除字符串首尾的空格

2. trimStart : 删除字符串首的空格

3. trimEnd : 删除字符串尾的空格

十一. split( swparator,limit ) : 字符串分割 

十二. Object.entries( )遍历

十三. 字符串填充

1 - padStart : 左边填充

2 - padEnd : 右边填充

十四. 处理 URL 的查询字符串 URLSearchParams -  | MDN


String - JavaScript | MDN

一. 访问字符串字符

const message = 'hello world'

console.log( message[1] ) // e
console.log( message.charAt(4) ) // o

二. 字符串遍历

1 -  普通循环

const message = 'hello world'

for (let i = 0; i < message.length; i++) {
     console.log(message[i])
}

2 - for...of循环

// for..of的遍历 -> 迭代器
// 目前可迭代对象: 字符串/数组
// 对象是不支持for..of
// String对象内部是将字符串变成了一个可迭代对象

for (let char of message) {
  console.log(char)
}

三. 修改字符串

当字符串定义后是不可以修改的,所以当直接操作字符是无效的

let message = "Hello World"

message[2] = "A"
console.log(message) // Hello World. 不会更改的

四. toUpperCase : 将所有字符变为大写

const message = 'hello'

console.log(message.toUpperCase()) // HELLO ,原来的字符串没有更改,而是生成了新的字符串

五. toLowerCase : 将所有字符变为小写

const message = 'HeLLo'

console.log(message.toUpperCase()) // hello,原来的字符串没有更改,而是生成了新的字符串

六. 查找字符串

1 - indexOf ( searchString , fromIndex ) : 查找

  • 情况一: 搜索到, 搜索字符串所在索引位置
  • 情况二: 没有搜索到, 返回-1
const message = 'my name is coder'

let index = message.indexOf('name')
if(index !== -1){
    console.log('找到了')
}else{
    console.log('没找到')
}

2 - includes( searchString , position ) : 查找

const message = 'my name is coder'

if(message.includes('name')){
    console.log('找到了')
}

3 - startsWith : 以xxx开头

const message = 'my name is coder'

if (message.startsWith("my")) {
   console.log("message以my开头")
}

4 - endsWith : 以xxx结尾

const message = 'my name is coder'

if (message.endsWith("coder")) {
   console.log("message以my结尾")
}

七. 替换字符串

1 - replace : 替换找到的第一个

  • 查找到对应的字符串,并且使用新的字符串进行替代
  • 也可以传入一个正则表达式来查找,也可以传入一个函数来替换
// 传入字符串
const message = 'my name is star'
let newMessage = message.replace("star", "kobe")
console.log(newMessage) // my name is kobe

// 传入函数
const newName = "kobe"
let newMessage = message.replace("star", function() {
  return newName.toUpperCase()
})
console.log(newMessage) // my name is KOBE

2 - replaceAll : 替换找到的所有

const info = 'my name is star, star star is good';
// 只替换找到的第一个
const onlyFirstOne = info.replace('star', 'coder');
console.log(onlyFirstOne); // my name is coder, star star is good

// 全部替换
const allChange = info.replaceAll('star', 'coder');
console.log(allChange); // my name is coder, coder coder is good

八. 获取子字符串 

const message = "Hello World"

console.log(message.slice(3, 7)) // lo W
console.log(message.slice(3, -1)) // lo Worl
console.log(message.slice(3)) // lo World

console.log(message.substr(3, 7)) // lo Worl

九. 拼接字符串

1 - + 

const str1 = "Hello"
const str2 = "World"
const str3 = "kobe"

const newString = str1 + str2 + str3
console.log(newString)

2 - concat

const str1 = "Hello"
const str2 = "World"
const str3 = "kobe"

// 可链式调用
const newString2 = str1.concat(str2).concat(str3)
// 可同时传入多个值
const newString3 = str1.concat(str2, str3, "abc", "cba")

十. trim

1. trim : 删除字符串首尾的空格

console.log("    star      abc   ".trim()) // star      abc

2. trimStart : 删除字符串首的空格

console.log("    star      abc   ".trimStart()) // star      abc___ 这里有空格的哈

3. trimEnd : 删除字符串尾的空格

console.log("    star      abc   ".trimEnd()) // ____star      abc

十一. split( swparator,limit ) : 字符串分割 

  • separator:以什么字符串进行分割,也可以是一个正则表达式;
  • limit:限制返回片段的数量;
const message = "abc-cba-nba-mba"
// 切割字符为 => -
const items = message.split("-")
console.log(items) // ['abc','cba','nba','mba']
// 通过数组的join方法,可变为字符串 连接字符为 *
const newMessage = items.join("*")
console.log(newMessage) // abc*cba*nba*mba

//-----------------------------------------------

const message = 'abc-cba-nba-mba';
// 返回长度为2的数组
const items = message.split('-', 2);
console.log(items); // ['abc','cba']

十二. Object.entries( )遍历

console.log(Object.entries('Hello')); // [['0', 'H'], ['1', 'e'], ['2', 'l'], ['3', 'l'], ['4', 'o']]

const str = 'Hello';
for (const item of Object.entries('Hello')) {
  const [index, value] = item;
  console.log(index, value); // 0 H | 1 e | 2 l | 3 l | 4 o |
}

十三. 字符串填充

padStart |padEnd (length,str)

  • length : 该字符串的总长度
  • str : 用什么字符来填充

1 - padStart : 左边填充

// 此时字符串长度为3
let info = 'abc';
// 设定拼接结束字符串总长度为5,不足部分用u来填充
info = info.padStart(5, 'xx');


let str = 'address';
// 如果字符串本身的长度>=传入的参数,则不改变
str = str.padStart(5, 'xx');
console.log(str); // address

2 - padEnd : 右边填充

let cardNumber = '132666200001018899';
// 截取前四位
const sliceNumber = cardNumber.slice(0, 4);
// 把除前四位外的其他数字用 **** 来填充
cardNumber = sliceNumber.padEnd(cardNumber.length, '*');
console.log(cardNumber); // 1326**************

十四. 处理 URL 的查询字符串 URLSearchParams -  | MDN

可用来获取地址栏上的 ? 后携带的数据

// 从地址栏上拿到数据,可用split切割一下 ?
const searchString = '?name=star&age=18&height=1.88';
// 处理 URL 的查询字符串
const params = new URLSearchParams(searchString);
// 啥也看不出来
console.log(params);
// 可直接拿到
console.log(params.get('name')); // star
console.log(params.get('age')); // 18
// 也啥都看不出来
console.log(params.entries()); // Iterator {}

// 但是可以遍历出来
for (const item of params.entries()) {
  console.log(item); // ['name', 'star']、['age', '18']、['height', '1.88']
}
// 所以直接在数组中解构
console.log([...params.entries()]); // [ ['name', 'star'], ['age', '18'], ['height', '1.88'] ]

// 转换成对象  也可以直接 Object.fromEntries(params)
const paramObj = Object.fromEntries(params.entries());
console.log(paramObj); // {name: 'star', age: '18', height: '1.88'}

// --------------------一步搞定--------------------
const searchStringTwo = '?name=liuli&id=8&info=havemoney';
const obj = Object.fromEntries(new URLSearchParams(searchStringTwo));
console.log(obj); // {name: 'liuli', id: '8', info: 'havemoney'}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值