1. 程式人生 > >JavaScript基礎知識(字符串的方法)

JavaScript基礎知識(字符串的方法)

null 去除 不變 獲取 默認 包含 right code lac

字符串的方法

1.字符串: 在js中被單引號或雙引號包起來的內容都是字符串;

var t = "true";
console.log(typeof t);// "string"
console.log(typeof true);// "boolean"
var str = "yyy./NIha";
var s = ‘www‘;
var str = "helloworld";

2.索引: 在字符串中,每一個字符都有一個與之對應的索引,這個索引是個數字,從0開始;

console.log(str[3]);// "f";

3.length :字符串有一個length屬性,屬性值代表當前字符串的字符的個數;

console.log(str.length);
//獲取一個字符串最後一個字符;
console.log(str[str.length - 1]);

4.字符串的運算; + - * /

- * /: 會先把字符串轉換成數字,然後再進行計算
console.log("6" - 2);// 4
console.log("5"/"4")// 1.25
console.log("5px"-"4")// NaN
console.log(true*"4")// 4

  1. 任何數字和NaN 計算,結果都是NaN;
  2. 任何數字和undefined運算,得到也是NaN;
+: 字符串拼接;
console.log("6px"+undefined);
console.log(NaN
+"undefined"); [] : 空數組在進行拼接時,會默認調用toString轉換成空字符串;然後拼接; var a = typeof 10 + true + [] + null + undefined+{}; // "numbertruenullundefined" console.log(a);

5、字符串方法

  1. 索引
  2. length
  3. 字符串運算

1. toUpperCase : 把小寫字母轉成大寫

str.toUpperCase() var str1 = “HELLO”

2.toLowerCase 把大寫轉小寫

console.log(str1.toLowerCase());

3.charAt : 通過索引獲取字符

console.log(str.charAt(4));

4.charCodeAt : 通過索引獲取對應字符的Unicode編碼;

a-z : 97–122 0-9 : 48-57 A-Z : 65-90 console.log(str.charCodeAt(0));

5.substr : 截取 substr(m,n) 從索引m開始,截取n個字符;

substr(m) : 從索引m開始截取到末尾 console.log(str.substr(2)); console.log(str.substr(2,5));

6.substring: substring(m,n) :從索引m開始,截取到索引n,不包含n;

當n是負數時,m截取到開頭; 不支持負數; console.log(str.substring(2, 5)); console.log(str.substring(5, -1));

7.slice(m,n): substring; 從索引m開始,截取到索引n,不包含n

支持負數的的截取; console.log(str.slice(3, 7)); console.log(str.slice(3, -1)); console.log(str.slice(3, 0));

8.indexOf : 檢測字符在字符串中第一次出現的索引位置;

返回索引;如果字符串不存在,返回-1; console.log(str.indexOf(“e”));// 4 console.log(str.indexOf(“w”));// -1

9.lastIndexOf : 檢測字符在字符串中最後一次出現的索引位置;

返回索引;如果字符串不存在,返回-1; console.log(str.lastIndexOf(“n”)); console.log(str.lastIndexOf(“k”));

10.split : 把字符串按照特定的字符分隔數組中的每一項;

console.log(str.split(“”)); var str = “zhufengpeixun”;

11.replace:替換;原有字符串不變;用新字符替換舊的字符

console.log(str.replace(“u”, “m”).replace(“u”, “m”)); 字符串.replace(oldStr,newStr); console.log(str); var str1 = “hellohello”; console.log(str1.replace(“hello”, “helloworld”).replace(“hello”, “helloworld”));//”helloworldworldhello”

12.concat : 拼接

var str = “aer”; console.log(str.concat(“123”));// “aer123”

13.trim : 去空格 : 去除字符串中左右的空格;

trimLeft : 去字符串左邊的空格 trimRight : 去字符串右邊的空格; var str = ” 66yy yww “; str.trim()

JavaScript基礎知識(字符串的方法)