中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

JavaScript String


String 對(duì)象用于處理已有的字符塊。


JavaScript 字符串

一個(gè)字符串用于存儲(chǔ)一系列字符就像 "John Doe".

一個(gè)字符串可以使用單引號(hào)或雙引號(hào):

實(shí)例

var carname="Volvo XC60";
var carname='Volvo XC60';

你使用位置(索引)可以訪問(wèn)字符串中任何的字符:

實(shí)例

var character=carname[7];

字符串的索引從零開(kāi)始, 所以字符串第一字符為 [0],第二個(gè)字符為 [1], 等等。

你可以在字符串中使用引號(hào),如下實(shí)例:

實(shí)例

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

或者你可以在字符串中使用轉(zhuǎn)義字符()使用引號(hào):

實(shí)例

var answer='It's alright';
var answer="He is called "Johnny"";

運(yùn)行代碼 ?

字符串(String)

字符串(String)使用長(zhǎng)度屬性length來(lái)計(jì)算字符串的長(zhǎng)度:

實(shí)例

var txt="Hello World!";
document.write(txt.length);

var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);

運(yùn)行代碼 ?

在字符串中查找字符串

字符串使用 indexOf() 來(lái)定位字符串中某一個(gè)指定的字符首次出現(xiàn)的位置:

實(shí)例

var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");

運(yùn)行代碼 ?

如果沒(méi)找到對(duì)應(yīng)的字符函數(shù)返回-1

lastIndexOf() 方法在字符串末尾開(kāi)始查找字符串出現(xiàn)的位置。


內(nèi)容匹配

match()函數(shù)用來(lái)查找字符串中特定的字符,并且如果找到的話,則返回這個(gè)字符。

實(shí)例

var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));

運(yùn)行代碼 ?

替換內(nèi)容

replace() 方法在字符串中用某些字符替換另一些字符。

實(shí)例

str="Please visit Microsoft!"
var n=str.replace("Microsoft","Runoob");

運(yùn)行代碼 ?

字符串大小寫(xiě)轉(zhuǎn)換

字符串大小寫(xiě)轉(zhuǎn)換使用函數(shù) toUpperCase() / toLowerCase():

實(shí)例

var txt="Hello World!";?????? // String
var txt1=txt.toUpperCase();?? // txt1 文本會(huì)轉(zhuǎn)換為大寫(xiě)
var txt2=txt.toLowerCase();?? // txt2 文本會(huì)轉(zhuǎn)換為小寫(xiě)

運(yùn)行代碼 ?

字符串轉(zhuǎn)為數(shù)組

字符串使用split()函數(shù)轉(zhuǎn)為數(shù)組:

實(shí)例

txt="a,b,c,d,e"?? // String
txt.split(",");?? // 使用逗號(hào)分隔
txt.split(" ");?? // 使用空格分隔
txt.split("|");?? // 使用豎線分隔?

運(yùn)行代碼 ?

特殊字符

Javascript 中可以使用反斜線()插入特殊符號(hào),如:撇號(hào),引號(hào)等其他特殊符號(hào)。

查看如下 JavaScript 代碼:

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);

在JavaScript中,字符串的開(kāi)始和停止使用單引號(hào)或雙引號(hào)。這意味著,上面的字符串將被切成: We are the so-called

解決以上的問(wèn)題可以使用反斜線來(lái)轉(zhuǎn)義引號(hào):

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);

JavaScript將輸出正確的文本字符串:We are the so-called "Vikings" from the north.

下表列出其他特殊字符,可以使用反斜線轉(zhuǎn)義特殊字符:

代碼 輸出
' 單引號(hào)
" 雙引號(hào)
\ 斜桿
n 換行
r 回車(chē)
t tab
b 空格
f 換頁(yè)

字符串屬性和方法

屬性:

  • length
  • prototype
  • constructor

方法:

  • charAt()
  • charCodeAt()
  • concat()
  • fromCharCode()
  • indexOf()
  • lastIndexOf()
  • match()
  • replace()
  • search()
  • slice()
  • split()
  • substr()
  • substring()
  • toLowerCase()
  • toUpperCase()
  • valueOf()

更多方法與屬性介紹可以參考:JavaScript String 對(duì)象