02.11 字符串

字符串運(yùn)算

  • a. 加法運(yùn)算
    var str1 = 'abc';
    var str2 = 'hello';
    console.log(str1+str2) //abchello
    console.log(str1+100) //abc100
    console.log(str1+[1,2,3]) //abc1,2,3
  • b.比較運(yùn)算:> < == === != !==
    // 1. 比較相等
    console.log('abc' == 'abc'); //true
    console.log('abc' == 'bac'); //false
    console.log(100 == '100') ; //true
    console.log(100==='100'); //false

比較大小:和python字符串比較大小的方式一樣

  • console.log('abc' > 'bd'); //false
  • console.log('z' > 'sh'); //true

字符串長度

console.log(str2.length);
var str3 = new String('abc');
console.log(str3);
var newStr = str3.big();
console.log(newStr);

charAt(index) 獲取下標(biāo)對(duì)應(yīng)的字符

console.log('hello'.charAt(0));

charCodeAt(index)

獲取下標(biāo)對(duì)應(yīng)的的編碼(JS中的字符也是采用的unicode的編碼)
console.log('hello'.charCodeAt(0));

concat(str1, str2, str3) 將字符串連接上去

將字符串和多個(gè)數(shù)據(jù)依次連接在一起產(chǎn)生一個(gè)新的字符串(相當(dāng)于+的功能)
console.log('hello'.concat('abc', 'aaa')); 

endWidth(str) 判斷字符串1是否以字符串2結(jié)尾

console.log('hello'.endsWith('llo'));

str.indexOf(str) 獲取字符串出現(xiàn)的下標(biāo)位置

console.log('hello'.indexOf('l'));

str.lastIndexOf(str) 獲取最后一次出現(xiàn)的位置

console.log('hello'.lastIndexOf('l'));

str.match(正則表達(dá)式) 相當(dāng)于python中re模塊中的match

var re_str = /\d{3}$/;
var result = '237'.match(re_str);
console.log( result,result[0], result['input']); 

repeat(num) 重復(fù)次數(shù),相當(dāng)于python中的乘

var str4 = 'abc';
console.log(str4.repeat(4));

replace(rgexp, newstr) 只替換滿足正則表達(dá)式條件的第一個(gè)字符串

console.log('adadada'.replace(/\w/, 'x'));

slice(startnum, endnum)

console.log('hello'.slice(0, 2));
console.log('hello'.slice(-3, -1));

split 字符串分割成數(shù)組

console.log('hello'.split('e'))
console.log('abc'.repeat(4));
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容