javascript基礎系列:字符串的常用方法 javascript基礎系列:字符串的常用方法

javascript基礎系列:字符串的常用方法

字符串的常用方法

所有用的單引號、雙引號、反引號包起來的都是字符串

1. charAt/charCodeAt

charAt:根據索引獲取指定位置的字符
charCodeAt: 獲取指定字符的ASCII碼值(UNicode編碼值)
@params
n[number] 獲取字符指定的索引
@return
返回查找到的字符(找不到返回的是空字符串不是undefined,或者對應的編碼值)

let str = 'zhufengpeiixunyangfangqihang';
console.log(str.charrAt(0)) // => Z

2. 'substr/substring/slice'

實現字符串截取
substr(n, m): 從索引n開始截取m個字符串,m不寫截取到末尾
substring(n, m): 從索引n開始找到索引m處(不含m),超過索引的也只截取到末尾,不支持負索引
slice(n,m):和substriing一樣,都是找到索引爲m處,但是slice可以支持負數作爲索引,其餘兩個方法是不可以的

let str = 'lanfengqiuqiu'
console.log(str.substr(3,2))
console.log(str.substring(3,5))

3. indexOf/lastIndexOf/includes()

驗證字符是否存在
indexOf(n,m):獲取n第一次出現位置的索引,m是控制查找的起始位置索引
lastIndexOf(x):最後一次出現位置的索引
沒有這個字符,返回結果是-1

let str = 'lanfengqiuqiu'
console.log(str.indexOf('n')) // 驗證第一次出現的位置,返回的索引
console.log(str.lastIndexOf('n'))
if(!str.includes('@')) {
    console.log('當前字符串不包含@')
}

4. toUpperCase/toLowerCase

字符串中字母大小寫轉換
toUpperCase():轉大寫
toLowerCase():轉小寫

5. split

split([分隔符]):把字符串按照指定的分隔符拆分成數組(和數組中的join相對應)
split方法支持傳遞正則表達式

//把|分隔符變成爲,分隔符
let str = 'music|movie|eat|sport'
let arr = str.split('|')
console.log(arr)
arr.join()

6. replace

replace(新字符,老字符):實現字符串的替換(經常伴隨着正則而用)

let str='嵐楓@秋秋@前端'
str = str.replace('@', '-') //在不使用正則表達式的情況下
console.log(str) // 嵐楓-秋秋@前端

// -----
let str='嵐楓@秋秋@前端'
str = str.replace(/@/g, '-') //在不使用正則表達式的情況下
console.log(str) // 嵐楓-秋秋@前端

7. match

localCompare
trim/trimLeft/trimRight
控制檯輸出String.prototype查看所有字符串中提供的方法

實現一些常用的需求

1. 時間字符串的格式化處理

// 方案一:用replace
let time = '2019-7-24 12:6:23'
// 變爲自己需要呈現的格式
// “2019年07月24日 12時06分23秒”
time.replace('-', '年').replace('-','月').replace('', ‘日’)
.replace(':', ‘時’).replace(':', '分') + ‘秒’;
console.log(time)

// 方案二
let addZero = val => val.length < 2 ? '0' + val : val
let time = '2019-7-24 12:6:23'
let ary = time.split(/(?: |-|:)/g)
time = ary[0]+ '年'+ addZero(ary[1]) + '月' + addZero(ary[2]) + '日'

2. 實現一個方法 queryUrlParams獲取一個URL地址問號後面傳遞的參數信息

let url = 'http://www.baidu.com?lx=1&name=lanfeng&teacher=aaa#box'
/**
    lx: 1,
  name:'lanfeng',
  teacher: 'aaa',
  hash: 'box'
**/

//1. 獲取問號後面的值
let askIndex = url.indexOf('?')
let wellIndex = url.indexOf('#')
let askText = url.substring(askIndex+1,wellIndex)
let wellText = url.substring(wellIndex+1)
console.log(askText, wellText)

//2.問號後面的值詳細處理
let result = {};
let askAry = askText.split('&');
console.log(askAry)
askAry.forEach(item => {
  let n = item.split('=')
  result[n[0]] = n[1]
})
result['hash']= wellText


//-----

/**
    *queryURLParams: 獲取URL地址中問號傳參的信息和哈希值
  * @params
    url[string]要解析的url字符串
  * @return
    [object]包含參數和哈希值信息的對象
**/
function queryURLParams(url) {
  let askIn = url.indexOf('?');
  let wellIn = url.indexOf('#');
  let askText = ''
  let wellText = ''
  wellIn === -1 ? wellIn = url.length : null
  askIn >=0 ? askText = url.substring(askIn+1 , wellIn) : null
    wellText = url.substring(wellIn+1)
  
  
  // 獲取每一部分信息
  let result = {}
  wellText !== '' ? result['hash'] = wellText : null
  if(askText !== '') {
    let ary = askText.split('&');
    ary.forEach(item => {
        let itemAry = item.split('=')
      result[itemAry[0]] = itemAry[1]
    })
  }
  return result
}
let url = 'http://www.baidu.com?lx=1&name=lanfeng&teacher=aaa#box'
let paramsObj = queryURLParams(url)
console.log(paramsObj)

3. 日期對象的基本操作

  1. 獲取當前客戶端(本地電腦)本地的時間
/**
 * 獲取當前客戶端(本地電腦)本地的時間
 * 這個時間用戶是可以自己修改的,所以不能作爲重要的參考依據
 * Thu Sep 10 2020 09:09:50 GMT+0800 (中國標準時間)
 * 獲取的結果不是字符串是對象數據類型的,屬於日期對象(或者說是Date這個類的實例對象)
**/
let time = new Date()

  1. 標準日期對象中提供了一些屬性和方法,供我們操作日期信息
  • getFullYear()獲取年
  • getMonth() 獲取月
  • getDate() 獲取日
  • getDay() 獲取日期
  • getHours() 獲取時
  • getMinutes() 獲取分
  • getSeconds() 獲取秒
  • getMilliseconds() 獲取毫秒
  • getTime() 獲取當前日期距離1970/1/1 00:00:00 這個日期之間的毫秒差
  • timetoLocaleDateString() 獲取年月日(字符串)
  • timetoLocaleString() 獲取完整的日期字符串
/**
 * queryDate:獲取當前的日期,把其轉換喂想要的格式
 * @params
 * @return
**/
function queryDate() {
  // 1. 獲取當前日期及詳細信息
    let time = new Date(),
      year = time.getFullYear(),
      month = time.getMonth() + 1
        day = time.getDate(),
      week = time.getDay(),
      hours = time.getHours(),
      minutes = time.getMinutes(),
      seconds = time.getSeconds();
  
  // 2. 拼湊成我們想要的字符串
  let weekAry = ['日', '一', '二', '三', '四', '五', '六']
  let result = year + "年" + addZero(month) + "月" + addZero(day) + "日"
  result += "星期" + weekAry[week] + " "
  
  result += addZero(hours)+ ":" + addZero(minutes)  + ":" + addZero(seconds);
  
}

/**
 * addZero:不足十補0
 * @params
 * @return
    處理後的結果(不足十位的補充零)
**/
function addZero(val) {
    val = Number(val);
  return val < 10 ? '0' + val : val
}
  1. new Date() 除了獲取本機時間,還可以把一個時間格式字符串轉化爲標準的時間格式
new Date("2019/7/26") // Fri Jul 26 2019 00:00:00 GMT+0800 (中國標準時間)
// 
/**
    * 支持的格式
  * yyyy/mm/dd
  * yyyy-mm-dd 這種格式在ie下不支持
**/



// ------
let time = '2019-5-30 12:0:0'
// => "2019年-5月30日 12:0:0"
/**
    * 字符串處理解決方法
**/
function  formatTime(time) {
  
  // 1. 先獲取年月日信息
    let ary = time.split(''),
      aryLeft = ary[0].split('-'),
      aryRight = ary[1].split(':');
  ary = aryLeft.concat(aryRight)
  
  // 2. 拼接成爲我們想用的格式
  let result = ary[0] + '年'+ addZero(ary[1]) + '月' + addZero(ary[2]) + '日';
  result += ' ' + addZero(ary[3]) + ':' + addZero(ary[4]) + ':' + addZero(ary[5])
  
  
}

formatTime(time)

/**
 * addZero:不足十補0
 * @params
 * @return
    處理後的結果(不足十位的補充零)
**/
function addZero(val) {
    val = Number(val);
  return val < 10 ? '0' + val : val
}

/**
    * 基於日期對象處理
**/
function formatTime2(time) {
    // 1. 把時間字符串轉換爲標準日期對象
  time =  time.replace(/-/g, '/')
  time = new Date(time)
  
  //2. 基於方法獲取年月日等信息
  let year = time.getFullYear(),
      month = addZero(time.getMonth() + 1),
      day = addZero(time.getDate()),
        hours = addZero(time.getHours()),
       minutes = addZero(time.getMinutes()),
       seconds = addZero(time.getSeconds())
  // 3. 返回想要的結果
  return year + '年' + month + '月' + day + '日' + ' ' + hours + ':' + minutes + ':' + seconds
  
}

  1. 封裝一個公用的時間字符串格式化處理的方式
String.prototype.formatTime = function formatTime(template) {
  typeof template === 'undefined' ? template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null
  // this: 要處理的字符串
  let MatchAry = this.match(/\d+/g)
  
  template = template.replace(/\{(d+)\}/g,(x, y)=> {
    let val = matchAryy[y] || '00'
    val.length < 2 ? val = '0' + val : null
    return val
  })
  return template
}

總結:

今天主要分享一些字符串的常用方法及實現一些常用的需求,時間字符串處理,日期對象的基本操作,封裝一個公用的時間字符串處理方式等等

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章