字符串是存儲字符的變量,字符串類型的變量在聲明的時候,需要放在一對英文的雙引號或單引號內,引號內的文本可以寫任意字符,如下:
var x='hello';
var y="world";
var x='_*&#!)';
1.1字符串常用的屬性
字符串的長度
我們可以通過字符串的length屬性得到字符串的長度,得到的長度為number類型
代碼示例:
var str1="hello world";
console.log(str1.length); //11
1.2字符串常用的方法
(1).字符串的拼接(連接)
多個字符串連接成一個字符串,可以使用英文加號+
var name="張三";
var outTxt="你好,我叫"+name;
console.log(outTxt); //你好,我叫張三
(2).字符串的檢索
indexOf(),用于返回某個指定的字符串值在字符串中首次出現的位置。
字符串常用的方法有哪些、該方法接收一個參數。該方法返回結果為一個整數。如果沒有找到匹配的字符串則返回-1;
語法:string.indexOf(str);
參數 | 類型 | 描述 |
---|---|---|
str | string | 必選。要檢索的字符串。 |
代碼示例:
var txt="hello world";
console.log(txt.indexOf("he")); //0
console.log(txt.indexOf("e")); //1
console.log(txt.indexOf("l")); //2 'l'在'hello world'中首次出現的位置下標是2
console.log(txt.indexOf("m")); //-1
(3).提取字符串的片段
slice()用于提取字符串中的片段,并在新的字符串中返回被提取的部分,該方法至少接收一個參數
語法: string.slice(start,end);
參數 | 類型 | 描述 |
---|---|---|
strat | number | 必須。要提取的片段的起始下標。可為負值 |
end | number | 可選。要提取的片段的結尾下標,如果不傳,則提取的字符串從開始下標到字符串結束。可為負值 |
代碼示例:
var txt="hello world";
console.log(txt.slice(3)); // lo world
console.log(txt.slice(3,8)); // lo wo
(4).替換字符串
js 字符串處理、replace()方法是用新的字符串替換原字符串中的字符或子串。該方法接收兩個參數。
語法:string.replace(regexp/substr,replacement)
參數 | 類型 | 描述 |
---|---|---|
regexp/substr | RegExp對象/string | 必需。被替換的字符串或被替換的模式的 RegExp 對象。 |
replacement | string | 必需。替換文本 |
備注:RegExp對象(正則表達式)會有專門的章節介紹
代碼示例:
var txt="hello world";
console.log(txt.replace('h','H')); //Hello world
console.log(txt.replace('l','L')); //heLlo world 這里只將txt中的第一個‘l’替換成了‘L’,如果要替換全部‘l’,要使用RegExp對象
console.log(txt.replace(/l/g,'L')); //heLLo worLd;
(5).把一個字符串分割成字符串數組
split()方法會把一個字符串按照特殊的分隔符分割,分割后的結果是一個字符串數組。
該方法至少接收一個參數,語法:string.split(separator,howmany)
參數 | 類型 | 描述 |
---|---|---|
separator | string | 必需。分割符,可以是字符串、字符或正則表達式。 |
howmany | number | 可選。 分割后返回的數組的最大長度。 |
js定義字符串?代碼示例:
var txt="How are you?";
console.log(txt.split(' ')); //['How','are','you?']var txt2="How are you doing today?";
console.log(txt2.split(' ',2)); //['How','are']
(6).提取字符串中指定數目的字符串
substr()方法用于提取字符串中指定數目的字符串。該方法至少接收一個參數。
語法:string.substr(start,length);
參數 | 類型 | 描述 |
---|---|---|
start | number | 必需。要提取的子串的起始下標。必須是數值。如果是負數,那么該參數聲明從字符串的尾部開始算起的位置。也就是說,-1 指字符串中最后一個字符,-2 指倒數第二個字符,以此類推。 |
length | number | 可選。子串中的字符數。必須是數值。如果省略了該參數,那么返回從 開始位置到結尾的字串 |
代碼示例:
var txt="hello world";
console.log(txt.substr(2,3)); //llo
console.log(txt.substr(2)); //llo world