字符串可以直接通過字符串字面量創(chuàng)建。這些字面量被單引號(hào)或雙引號(hào)包裹。反斜線(\
)轉(zhuǎn)義字符并且產(chǎn)生一些控制字符。例如:
'abc'
"abc"
'Did she say "Hello"?'
"Did she say \"Hello\"?"
'That\'s nice!'
"That's nice!"
'Line 1\nLine 2' // 換行
'Backlash: \\'
可以通過方括號(hào)訪問單個(gè)字符:
> var str = 'abc';
> str[1]
'b'
length屬性是字符串的字符數(shù)量。
> 'abc'.length
3
提醒:字符串是不可變的,如果你想改變現(xiàn)有字符串,你需要?jiǎng)?chuàng)建一個(gè)新的字符串。
字符串可以通過加號(hào)操作符(+
)拼接,如果其中一個(gè)操作數(shù)為字符串,會(huì)將另一個(gè)操作數(shù)也轉(zhuǎn)換為字符串。
> var messageCount = 3;
> 'You have '+messageCount+' messages'
'You have 3 messages'
連續(xù)執(zhí)行拼接操作可以使用 +=
操作符:
> var str = '';
> str += 'Multiple ';
> str += 'pieces ';
> str += 'are concatenated.';
> str
'Multiple pieces are concatenated.'
字符串有許多有用的方法。例如:
> 'abc'.slice(1) // 復(fù)制子字符串
'bc'
> 'abc'.slice(1, 2)
'b'
> '\t xyz '.trim() // 移除空白字符
'xyz'
> 'mj?lnir'.toUpperCase()
'MJ?LNIR'
> 'abc'.indexOf('b') // 查找字符串
1
> 'abc'.indexOf('x')
-1
更多建議: