日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

【javascript高级教程】JavaScript 字符串(String) 对象

發布時間:2023/12/2 javascript 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【javascript高级教程】JavaScript 字符串(String) 对象 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

String 對象用于處理已有的字符塊。

JavaScript 字符串

一個字符串用于存儲一系列字符就像 "John Doe".

一個字符串可以使用單引號或雙引號:

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

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

var character=carname[6];

字符串的索引從零開始, 所以字符串第一字符為 [0],第二個字符為 [1], 等等。

你可以在字符串中使用引號,如下實例:

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

或者你可以在字符串中使用轉義字符(\)使用引號:

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

字符串(String)

字符串(String)使用長度屬性length來計算字符串的長度:

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

在字符串中查找字符串

字符串使用 indexOf() 來定位字符串中某一個指定的字符首次出現的位置:

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

如果沒找到對應的字符函數返回-1

lastIndexOf() 方法在字符串末尾開始查找字符串出現的位置。

內容匹配

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

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

替換內容

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

str="Please visit Microsoft!" var n=str.replace("Microsoft","孫叫獸666");

字符串大小寫轉換

字符串大小寫轉換使用函數?toUpperCase()?/?toLowerCase():、

var txt="Hello World!"; // String var txt1=txt.toUpperCase(); // txt1 文本會轉換為大寫 var txt2=txt.toLowerCase(); // txt2 文本會轉換為小寫

字符串轉為數組

字符串使用split()函數轉為數組:

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

特殊字符

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

查看如下 JavaScript 代碼:

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

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

解決以上的問題可以使用反斜線來轉義引號:

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

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

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

字符串屬性和方法

屬性:

  • length
  • prototype
  • constructor

方法:

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

?

總結

以上是生活随笔為你收集整理的【javascript高级教程】JavaScript 字符串(String) 对象的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。