字符串定義和基本方法介紹

第一部分:

字符串定義: 它是編程語言中的一種基本數(shù)據類型,它由數(shù)字、字母、下劃線組成的一串字符,通常以串聯(lián)的整體作為操作對象.
  • 定義擴展延伸:

組成的字符可以是 零個 或 多個, 放在 單引號 或者 雙引號之間. 如果字符串里面有單引號子內容,則整個字符串就要用 雙引號.(如果非要單引號里面使用單引號,那就必須使用 反斜杠 \ 來把引號轉義掉)

//雙/單引號
var str3 = 'hel'l'o world'
console.log(str3) //  "error"

var str4 = "hel'l'o world"
console.log(str4)  // "hel'l'o world"

// 反斜杠轉義
var str5 = "hel'l'o world"
var str6 = 'a\'b\'c'

console.log(str5)  //"hel'l'o world"
console.log(str6)  // "a'b'c"

空格也會占用空間,影響字符串的長度. 如下:

var str1 = 'hello world'
var str2 = 'hello w o rld'
console.log(str1.length) // 11
console.log(str2.length) // 13

字符串格式形式一般都是在同一行內, 如果非要在多行來表示一個字符串,就要用到
①空格+反斜杠 (不推薦)
②使用 + 符號來連接 (推薦)

var str7 = 'hello \
world \
ni \
hao';
console.log(str7) // "hello world ni hao" 


var str8 = 'hello'
+ ' world'
+ ' ni'
+ ' hao';
console.log(str8) // "hello world ni hao"

字符串多行顯示方法,使用 `(數(shù)字1左邊鍵)小斜點, 這是ES6新增功能

var str9 = `hello 
world
ni 
hao
`
console.log(str9) 
               // 輸出結果為:
                          "hello 
                           world
                           ni 
                           hao
                            "

 

第二部分:

為了方便記憶,我們把字符串的基本方法先分類: 查 ,增, 刪, 改, 轉

  • 長度: string.length
var str1 = 'abc 123'
console.log(str1.length) // 6 注意空格也算一個單位長度
  • 通過索引值來查看所在字符 str[num]
var str = 'hello world '
console.log(str[3]) // "l"

// 注意 這個方法 不能實現(xiàn) 通過賦值來改變 字符串 ,如下:
var str = 'hello world '
str[3] = 'w'
console.log(str) //   "hello world " 原數(shù)組不改變, 賦值無效
  • 通過索引值查來找字符: string[num] ; string.charAt(num)
var str = 'hello world'
var str1 = str[2]
var str2 = str.charAt(4)
var str3 = str[20]  // 詢查不到返回 undefined 
var str4 = str.charAt(20) // 詢查不到返回 "" 

console.log(str1) // "o"
console.log(str2) // "o"
console.log(str3) // undefined 
console.log(str4) // ""
  • 通過字符來查找索引值: string.search('char') ; string.indexOf('char') ; string.lastIndexOf('char')
var str = 'hello world'
var search = str.search('l')
var search1 = str.search('a') // 查詢不到 返回 -1
var index = str.indexOf('o')
var index1 = str.indexOf('a')  // 查詢不到 返回 -1
var lastIndex = str.lastIndexOf('l')

console.log(search) //2
console.log(search1) //-1
console.log(index)  //4
console.log(index1)  //-1
console.log(lastIndex)  //9
  • string.match('chars') 匹配原數(shù)組chars,如果存在,以數(shù)組返回chars,不存在 返回 null
var str = 'hello world '
var matchStr = str.match('el')
console.log(matchStr) // ["el"]

var matchStr1 = str.match('le')
console.log(matchStr1) // null

  • 遍歷一個字符串,是ES6 新增: for ( .. of ..)
var str = 'hello world'
for (var i of str){
  console.log(i)
}
// "h" "e" "l" "o" " " "w" "o" "r" "l" "d"

// 或者 封裝成函數(shù)
function ergStr(string){
  for (var i of string){
    console.log(i)
  }
}
ergStr(str) // "h" "e" "l" "o" " " "w" "o" "r" "l" "d"
  • 查看某字符出現(xiàn)的次數(shù) 函數(shù) countchar(str,c) :
var str = ' hellw world'
function countchar(str,c){
  count = 0
  for (var char of str){
    if( char == c){
      ++count 
    }
  }
   console.log(count)
}

countchar(str,'l') // 3

  • ''+'' 運算符來 增添字符, 簡便,實用 前后都可添加 :
var str = 'hello world'
var strplus = str+'www'
console.log(strplus) // "hello worldwww"

var plusstr = 'ni hao '+str
console.log(plusstr)  // "ni hao hello world"

  • string.concat('chars') 增添字符
var str = 'hello world'
var strconcat = str.concat('yyy')
console.log(strconcat) // ""hello worldyyy""
  • string.replace('char','replacechars') 這個是一個變相的增添,可以在定位的字符后面來添加字符串
var str = 'hello world '
var strPlaceAdd = str.replace('lo','lo this')
console.log(strPlaceAdd) // "hello this world "

刪 : 可以刪除字符 或 字符段 還是 空格

  • 使用repalce來刪除某一個或一段字符, 原字符串不變; 還可以用來刪除字符串所有的空格
var str =  'hello world '
var deleteStr = str.replace('e','')
console.log(deleteStr) // " hllo world "

var deleteStr1 = str.replace('ell','')
console.log(deleteStr1) // " ho world "

// 刪除所有字符串里所有空格
var deleteSpace = str.replace(/\s*/g,'')
console.log(deleteSpace) // "helloworld"
  • string.trim()刪除兩邊空格,原字符串不變
var str = ' hello world '
var trimStr = str.trim()
console.log(trimStr) // "hello world"

改: 可以引申為 改變,截取,限縮 字符串

  • string.substring(startIndex, endIndex) 截取元素一段字符串, 不改變原數(shù)組, 注: 截取不包括endIndex所在字符
var str = 'hello world '
var substring = str.substring(3,8)
console.log(substring)  // "lo wo"  注: 截取不包括endIndex所在字符
  • string.substr(startIndex, length) 從開始索引值截取一段長度的字符串,元字符串不變
var str = 'hello world '
var substr = str.substr(3,8)
console.log(substr)  / "lo world"
  • string.slice(startIndex,endIndex) 截取startIndex 到 endIndex 的字符段, 不包括endIndex所在字符
var str = 'hello world '
var sliceStr = str.slice(3,8)
console.log(sliceStr) // "lo wo"

//注意 slice 允許負數(shù)索引值的出現(xiàn), 表示 倒數(shù)的索引值: 
var sliceStr1 = str.slice(3,-2)
console.log(sliceStr1) // "lo worl"
var sliceStr2 = str.slice(-4,-1)
console.log(sliceStr2) // "rld"
  • string.toUpperCase() 和 string.toLowerCase() 全局改變字符成大/小寫
var str =  'Hello World '
var upperStr = str.toUpperCase()
var lowerStr = str.toLowerCase()
console.log(upperStr) // "HELLO WORLD "
console.log(lowerStr) // "hello world "

//如果要想改變某個字符的大小寫 就用 .replace() 如: 
var reStr = str.replace('lo','LO')
console.log(reStr) // "HelLO World "

字符串與數(shù)字,數(shù)組,對象的類型轉換

  • 轉成 數(shù)字類型:
    ① parseInt( string ) : 轉換為整數(shù), 忽略小數(shù)點后面數(shù)字 以及 忽略字符串
    ② parseFloat( string) : 轉換為浮點型數(shù)字,遇到非數(shù)字自動舍去,只認識第一個小數(shù)點,后面的小數(shù)點自動舍去
    ③ Number(string) : 強制轉換為數(shù)字, 不能有非數(shù)字以外類型, 否則返回NaN
var str = '123px'
var floatStr = '123.123px'

// parseInt()
var intNum = parseInt( str )
var intNum1 = parseInt( floatStr )
console.log( intNum )  // 123 
console.log( intNum1 ) // 123

// parseFloat()
var floatNum = parseFloat( floatStr )
console.log( floatNum ) // 123.123

// 注意 parseFloat 只能識別到第一個小數(shù)點,如下: 
var floatStr1 = '123.456.789px'
var floatNum1 = parseFloat( floatStr1 )
console.log( floatNum1 ) // 123.456

// Number()
var num = Number(str)
console.log( num ) // NaN

//  數(shù)值 轉 字符串 
var num = 123456
var numStr1 = num + ''
var numStr2 = num.toString()
console.log(numStr1) // "123456"
console.log(numStr2) // "123456"
  • 轉成 數(shù)組類型 string.split('separator')
var str = '123,abc,DEF'
var arrStr = str.split(',')
console.log(arrStr) // ["123", "abc", "DEF"]
console.log(str) //  "123,abc,DEF" 不改變原字符串

var arrStr1 = str.split("")
console.log(arrStr1 ) // ["1", "2", "3", ",", "a", "b", "c", ",", "D", "E", "F"]

// 注意 match()方法也是返回一個數(shù)組
var matchStr = str.match('3,a')
console.log( matchStr ) // ["3,a"]

// 數(shù)組 轉換 字符串方法
var arr = ['abc','123','DBC']
var arrStr = arr.join('')
console.log( arrStr ) "abc123DBC"

  • 轉成 對象類型 JSON.parse(string)
var str = '{"name": "li", "age": 18, "sex": "male"}'
var objStr = JSON.parse(str)
console.log( objStr ) // { age: 18, name: "li",sex: "male"}

// 對象 轉換 字符串方法
var reStr = JSON.stringify( objstr )
console.log( reStr ) // "{"name":"li","age":18,"sex":"male"}"
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容