js字串的一些操作方法

2021-10-23 08:35:08 字數 3358 閱讀 2275

一部分的字串的操作方法

1.concat:用於字串的拼接

var aa =

"hello"

var bb =

"world"

var cc = aa.

concat

(bb)

;//cc= helloworld

2.slice(x,y):擷取字串,第乙個x表示開始擷取的位置,y表示結束擷取的位置,不包含索引為y的

var dd = aa.

slice(0

,3);

//dd= hel

3.substr(x,y):擷取字串,第乙個x開始擷取的位置,y是表示要擷取的個數

var ee = aa.

substr(0

,4);

//ee=hell

4.tofixed(x):四捨五入取小數方法,x:表示保留2位小數

var  a=

2var b =

3var c =

(a/b)

.tofixed(2

);//c=0.67

5.indexof查詢字串

indexof() 方法可返回某個指定的字串值在字串中首次出現的位置。

引數:要查詢的字串的值

返回值:第一次出現的位置,沒有則返回-1.

例如:

var str =

"asdfghj"

;var index = str.

indexof

("dfg");

//index的值是2

6.substring擷取指定字串

substring() 方法用於提取字串中介於兩個指定下標之間的字元。

引數:要擷取的字串位置

返回值:乙個新的字串

例如:

var str=

"hello world!"

var val = str.

substring(1

,7);

//val的值是ello w

var str2 =

"hello world!"

var val2 = str2.

substring(1

);//val2的值是ello world!

7.touppercase把字串轉換為大寫

var str=

"abc def!"

console.

log(str.

touppercase()

)//abc def!

8.tolowercase把字串轉換為小寫

var str=

"abc def!"

console.

log(str.

tolowercase()

)//abc def!

9.tolocaleuppercase把字串轉換為大寫

var str=

"abc def!"

console.

log(str.

tolocalelowercase()

)//abc def!

10.split把字串分割為字串陣列。

var str=

"abc def ghi jkl"

console.

log(str.

split

(" "))

//["abc", "def", "ghi", "jkl"]

console.

log(str.

split(""

))//["a", "b", "c", " ", "d", "e", "f", " ", "g", "h", "i", " ", "j", "k", "l"]

console.

log(str.

split

(" ",3

))//["abc", "def", "ghi"]

11.search方法用於檢索字串中指定的子字串

search() 方法用於檢索字串中指定的子字串,或檢索與正規表示式相匹配的子字串。要執行忽略大小寫的檢索,請追加標誌 i。如果沒有找到任何匹配的子串,則返回 -1。

var str=

"abc def!"

console.

log(str.

search

(/def/))

//4

11.replace方法用於在字串中用一些字元替換另一些字元,或替換乙個與正規表示式匹配的子串

var str=

"abc def!"

console.

log(str.

replace

(/abc/

,"cba"))

//cba def!

12.match() 方法可在字串內檢索指定的值,或找到乙個或多個正規表示式的匹配

該方法類似 indexof() 和 lastindexof(),但是它返回指定的值,而不是字串的位置。

var str=

"1 abc 2 def 3"

console.

log(str.

match

(/\d+/g))

//123

13.charcodeat返回在指定的位置的字元的 unicode 編碼。

var str=

"abc"

console.

log(str.

charcodeat(1

))//98

14.charat返回在指定位置的字元

var str=

"abc"

console.

log(str.

charat(0

))//a

字串的一些操作方法

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...

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

var str this is a eg str.indexof is 返回2 存在則返回出現位置的索引 str.indexof sss 返回 1 不存在則返回 1 str.lastindexof is 返回5 從後往前檢索 str.lastindexof sss 返回 1var str 01234...