字符串
字符串就是零個或多個排在一起的字符,放在單引號或雙引號之中。
'abc'
"abc"
單引號字符串的內部,可以使用雙引號。雙引號字符串的內部,可以使用單引號。
'key="value"'
"It's a long journey"
多行與轉義
如果要在單引號字符串的內部,使用單引號(或者在雙引號字符串的內部,使用雙引號),就必須在內部的單引號(或者雙引號)前面加上反斜杠,用來轉義。
'Did she say \'Hello\'?'
// "Did she say 'Hello'?"
"Did she say \"Hello\"?"
// "Did she say "Hello"?"
注意: 轉義符在js中不計算長度
var str = "d\'rg\\a"
console.log(str) //"d'rg\a"
console.log(str.length) //6
字符串多行
字符串長度較長時,可拆成多行,換行符之前需使用轉義符號
var a = 'hel
\'llo' //error
var a = 'hel\
\'llo'
console.log(a) // "hel'llo"
字符串換行更安全的寫法
var longstring = 'long'
+ 'long'
+ 'long'
+ 'string'
console.log(longstring) // "longlonglongstring"
ES6處理長字符串方法
`
hello
ddd
`
/* hello
ddd
*/
字符串常用方法
以下是常用方法
var str = "hello";
console.log( str.length );
console.log( str[0] );
console.log( str[str.length - 1] );
console.log( str.charAt(0) );
console.log( str.charCodeAt(0) );
var str2 = " world";
var str3 = str1 + str2; //字符串拼接
var color = 'red'
var str4 = '衣服的顏色' + color
var str5 = '衣服的顏色${color}'
console.log(str4) //"衣服的顏色red"
console.log(str5) //"衣服的顏色red"
cosnole.log( str3 );
console.log(str.charAt(1)) //"e"
console.lgo(str.charCodeAt(1)) //101 返回字符串的ASCII碼
字符串截取 可實現字符串偽刪除
var str = "hello world";
var sub1 = str.substr(1, 3); // 第一個是開始位置, 第二個是長度 ell
var sub2 = str.substring(1, 3); // 第一個是開始位置,第二個是結束位置,長度為第二個-第一個 el
var sub3 = str.slice(1, 3); // 同上 允許負參
var sub2 = str.slice(0,-1)
console.log(sub3) //"hello worl" 實現字符串偽刪除效果
console.log(str) //"hello world" 均不會改變原數組
查找
var str = "hello my world";
var s1 = str.search('my'); //6 找不到為-1
str.indexOf('my') //6 效果于.search類似
var s2 = str.replace('my', '[1, 7, 2]') //"hello [1, 7, 2] world" 把replace(v1, v2)中v1替換為v2
var s4 = str.replace('my','')
console.log(s4) //"hello world" 使用replace實現刪除字符串效果
var s3 = str.match('my'); //返回匹配的數組 常配合正則表達式使用
console.log(str) //"hello my world"
大小寫
var str = 'hello my world'
console.log(str.toUpperCase()) //"HELLO MY WORLD"
console.log(str) //"hello my world" 不改變原數組
console.log(str.toLowerCase()) //hello my world
console.log(str) //"hello my world" 不改變原數組