js 一些常見的字串的操作方法 歸納總結一下

2021-09-26 15:21:52 字數 4054 閱讀 7229

var str=

"this is a eg"

;str.

indexof

("is"

)===

>

返回2(存在則返回出現位置的索引)

str.

indexof

("sss"

)===

>返回-

1(不存在則返回-1)

str.

lastindexof

("is"

)===

>返回5

//從後往前檢索

str.

lastindexof

("sss"

)===

>返回-

1

var str=

"0123456789"

str.

substring(2

,8)===

>返回'234567'

(獲取的字串包括開始位置,不包括結束位置)

str.

substring(2

)===

>返回"23456789"

str.

substring(-

5)===>返回"0123456789"

var str=

"0123456789"

str.

slice(2

,8)===

>返回"23456789"

(第二個引數為你需要的字串的長度)

str.

slice(2

)===

>返回"23456789"

str.

slice(-

5)===>返回"56789"!!

!區別於substring

var str=

"0123456789"

str.

substr(2

,8)===

>返回'234567'

(獲取的字串包括開始位置,不包括結束位置)

str.

substr(2

)===

>返回"23456789"

str.

substr(-

8)===>返回"56789"!!

!區別於substring

str.

substr(-

8,-2

)===

>返回"234567"

str.

substr(-

2,-8

)===

>返回""

var str =

"0123456789"

;var str =

" 我 需 要 去 除 空 格 ";!

!!!只能去除首尾兩端的空格;

var newstr = str.

trim()

;console.

log(newstr)

;方法二:

正規表示式(!

!!去除所有的空格)

;var str =

" 我 需 要 去 除 空 格 "

;var newstr = str.

replace

(/\s*/g,""

);console.

log(newstr)

;

var str=

'012abc中文'

str.

charat(6

)===

>返回"中"

//存在該索引就返回該字元

str.

charat(10

)===

>返回""

//不存在返回空字串

str.

charcodeat(6

)===

>返回20013

//返回的是該字元的ascii碼

str.

charcodeat(10

)===

>返回nan

//不存在返回nan!!!!!!不是空或者null

var str=

'空山新雨後'

str.

startswith

('空'

)===

>返回true

str.

startswith

('山'

)===

>返回false

str.

endswith

('後'

)===

>返回true

str.

endswith

('空'

)===

>返回false

var str=

'abcd你好efgh'

str.

touppercase()

===>返回"abcd你好efgh"

str.

tolowercase()

===>返回"abcd你好efgh"

var a =[1

,2,3

];var b =[4

,5,6

];var c = a.

concat

(b);

c =[1,

2,3,

4,5,

6];//拼接陣列

//用法  str.match(正規表示式或者正則物件)

var str=

"this is a eg"

;var reg=

/\w+/g

str.

match

(reg)

===>返回(

4)?[

"this"

,"is"

,"a"

,"eg"

] 本身是乙個陣列

正則的exec方法與他相同

eg reg.

exec

(str)

===>返回 [

"this"

] 就算是全域性匹配,也只返回第乙個;

ar str=

" 12454 this is a eg"

;var reg=

/\w+/g

str.

search

(reg)

===>

3 返回匹配的位置的索引

str.

search

(124

)===

>

3

var str=

" 12454 this is a eg"

;var reg=

/\w+/g

str.

replace

(reg,

'你好'

)===

>

" 你好 你好 你好 你好 你好" 返回替換後的字串

str.

replace

('124'

,'你好'

)===

>

" 你好54 this is a eg"

ar str=

"12454 this is a eg"

var reg=

/\s+/g

str.

split

(reg)

===>

["12454"

,"this"

,"is"

,"a"

,"eg"

] 返回匹配的位置的索引

str.

split(54

)===

>

["124"

," this is a eg"

]

js字串的一些操作方法

一部分的字串的操作方法 1.concat 用於字串的拼接 var aa hello var bb world var cc aa.concat bb cc helloworld2.slice x,y 擷取字串,第乙個x表示開始擷取的位置,y表示結束擷取的位置,不包含索引為y的 var dd aa.s...

字串的一些操作方法

public boolean equals object anobject public boolean equalsignorecase string,anotherstring public intcompareto string anotherstring compareto 方法的返回值是乙...

js字串的操作方法

1 charat 根據字元的下標返回相應小標上的字元 var str 憤怒的小鳥 console.log str.charat 2 結果為 的 2 charcodeat 根據字元的下標返回相應下標上的字元對應的編碼 console.log str.charcodeat 3 23567 3 strin...