一.監測字元串長度
var a='213412'
console.log(a.length) //6
二:JavaScript中常用的string對象的方法
屬性 | 說明 |
---|---|
charAt() | 傳回指定位置的字元串,空格占位 |
replace() | 用字元替代另一些字元 |
split() | 把一個字元串分割成字元串數組 |
indexOf() | 傳回某個指定的字元串 在字元串中首次出現的位置,沒有出現傳回-1 |
lastIndexOf() | 傳回某個指定字元串最後出現的位置 |
match() | 比對,在字元串中檢索指定的值 ,沒有為null |
toLowerCase() | 轉換為小寫 |
toUpperCase() | 轉化為大寫 |
slice() | 數組和字元串都能用,提取某個字元串的某一部分,并以新的字元串傳回并提取的部分 |
substr() | 從索引号提取指定數目的字元(開始位置,提取數量) |
substring() | 同slice() |
trim() | 删除前置和後置的空格 |
toFixed() | 保留小數 |
search() | 檢索字元串中,指定的字元串,或者是說,檢索與正規表達式比對的字元串 |
方法如下:
charAt()
var txt='hello world';
console.log(txt.charAt()); //h
console.log(txt.charAt(4)); //o
replace()
var txt='hello world';
txt=txt.replace('hello','happy');
console.log(txt) //happy world
split()
var txt='hello world';
console.log(txt.split('')); //按照所寫内容分割
//輸出結果:['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
indexOf()
var txt='hello world';
console.log(txt.indexOf('hello')); //0
console.log(txt.indexOf('world')); //6
console.log(txt.indexOf('1')); //-1
lastIndexOf()
var txt='hello world hello world ';
console.log(txt.lastIndexOf('hello')); //12
console.log(txt.lastIndexOf('world')); //18
console.log(txt.lastIndexOf('Hello')); //沒有找到為-1
match()
var txt='hello world hello world ';
console.log(txt.match('hello'));
console.log(txt.match('Hello'));
toLowerCase()
var txt='hello WORLD HELLO world ';
console.log(txt.toLocaleLowerCase())
toUpperCase()
var txt='hello WORLD HELLO world ';
console.log(txt.toUpperCase())
slice()
var txt='hello WORLD HELLO world ';
console.log(txt.slice(3,7)) //lo W 傳回第3-7位之間的字元
substr()
var txt='hello WORLD HELLO world ';
console.log(txt.substr(3,7)) //從第三位開始往下提取個
substring()
var txt='hello WORLD HELLO world ';
console.log(txt.substring(3,7)) //lo W 傳回第3-7位之間的字元
trim()
var txt=' hello WORLD HELLO world ';
var aa=txt.trim();
console.log(txt) //之間輸出
console.log(aa) //删除前後置空格輸出
toFixed()
var aa=1234.72422;
console.log(aa.toFixed(2)) //1234.72 保留兩位小數
search()
var txt='hello WORLD HELLO world';
document.write(txt.search(/h/))
document.write(txt.search(/world/i)) //大小寫不敏感的比對