mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
714 字
2 分钟
String 方法整理
2021-02-19

字符串的所有方法都会返回一个新字符串,不会修改原始字符串
字符串 + 任意类型 都会强制 toString() 基本包装类型: String、Number、Boolean

获取字符串某一字符#

原始: str.charAt(索引值)
H5: str[索引值]

字符串操作方法#

方法释义
contact()拼接字符串,等效于 ++ 更常用
slice(start[, end])start 位置开始,截取到 end 位置,end 取不到
substring(start[, end])start 位置开始,截取到 end 位置,end 取不到
substr(start[, length])start 位置开始,截取 length 个字符
trim()去除字符串前后的空格
replace(regexp/substr, newSubStr/function)只替换找到的第一个字符,regexp 匹配到的内容或 substr 会被 newSubStrfunction 的返回值替换
toUpperCase()将小写字母转换为大写
toLowerCase()将大写字母转换为小写
indexOf(searchValue [, fromIndex])fromIndex 开始,从前往后查找 searchValue,没找到返回 -1
lastIndexOf(searchValue[, fromIndex])fromIndex 开始,从后往前查找 searchValue,没找到返回 -1
padStart(targetLength [,padString])str.length 不足 targetLength 时,用 padString 在左侧重复填充,padString 过长时只保留左侧部分,可用作日期格式化
str.charCodeAt(index)返回字符串 strindex-1 位的的 ASC 码,为 Number
String.fromCharCode(num)返回 num 在 ASC 中对应的字符,为 String

split(str)#

依据str匹配到的字符切割字符串

'worry'.split('r')
// 结果:['wo','','',y]

例一:将worry替换为wo!!y的两种方法#

不使用 split

const str = "worry";
for ( let item of str ) {
const index = str.indexOf( "r" );
index !== -1 && ( str = str.replace( "r", "!" ) );
}

使用 split:

"worry".split( "r" ).join( "!" ); // "wo!!y"

例二:去除字符串中间空格#

" w o r r y ".split( " " ).join( "" ); // "worry"

substring 和 slice 的区别#

substring(start,stop)#

  • start等于stop时 返回空字符串。
  • stop可选:如果省略该参数,那么返回的子串会一直到字符串的结尾。
  • 如果start>stopsubstring会交换着两个参数,即从end参数开始截取到start-1位置结束。
  • 如果start或者stop中任意一个值大于字符串长度(length),那么这个值将会被字符串的长度替换。替换后看是否满足条件3,满足则走继续第3步。
  • 如果startstop中任意一个值为负数(<0)或者是 NaN(非数字),那么这个值会当做0来处理。

slice(start,stop):#

  • start 等于 stop 时 返回空字符串,和 substring 是一样的效果。

  • stop 可选:如果省略该参数,那么返回的子串会一直到字符串的结尾。和 substring 一样效果。

  • 如果 start > stopslice 不会交换着两个参数位置,而是直接返回空 ""

  • 如果 start 或者 stop 中任意一个值大于字符串长度(length),那么这个值将会被字符串的长度替换。和 substring 一样效果。

  • 如果start是负数(<0):那么截取字符串将会以字符串长基准,向前减start绝对值个字符串开始到stop处结束。
    例:bc 从 6-5 开始到 3 处结束,6 为字符串长度 等同于 slice(1,3);

"abcdef".slice( -5,3 ); // "bc"

如果 stop 是负数:那么会替换 stop( length - 1 ) - math.abs( stop );

"abcdef".slice( 1,-2 ); //bcd, 从 1 开始 到 6 - 1 - 2 = 3 处结束
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

String 方法整理
https://marrydream.top/posts/web前端/string-方法整理/
作者
茉铃
发布于
2021-02-19
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录