匹配輸入的字元:以字母或_開頭,後面由數字字母_組成長度為5-20的字元串 var reg=/^[a-bA-B_][a-bA-B0-9_]{4,19}/ var name1='abb' console.log(reg.test(name1) 題目描述:js求字元串位元組長度方法 描述:漢字位元組為2,其 ...
匹配輸入的字元:以字母或_開頭,後面由數字字母_組成長度為5-20的字元串
var reg=/^[a-bA-B_][a-bA-B0-9_]{4,19}/
var name1='abb'
console.log(reg.test(name1)
題目描述:js求字元串位元組長度方法
描述:漢字位元組為2,其他為1
一個英文字母(不分大小寫)占一個位元組的空間,一個中文漢字占兩個位元組的空間。英文標點占一個位元組,中文標點占兩個位元組
只有中文的Unicode編碼大於255
var str = 'jg78*笑笑';
方法1:
function getByteLength1(str){
var count = 0;
for(var i = 0;i < str.length;i ++){
if(str.charCodeAt(i) > 255){//charCodeAt返回參數Unicode編碼
count +=2;//中文為2Byte
}else{
count ++;//其他為1Byte
}
}
return count;//返回參數位元組長度值,也可以直接console輸出
}
方法2:
// 中文和英文一起,不分開討論
function getByteLength2(str){
var count = str.length;//首先count等於字元串的長度
for(var i = 0;i < str.length;i ++){
if(str.charCodeAt(i) > 255){//如果Unicode編碼大於255為中文
count ++;//在原來基礎上沒多一個中文就+1
}
}
return count;//返回參數位元組長度值,也可以直接console輸出
}
var res = getByteLength1(str);
console.log(res);
/*
代碼實現outerHTML
*/
Object.prototype.outerHTML=function(){
var innerCon = this.innerHTML;
outerCon = this.appendChild(innerCon);
alert(outerCon)
}
var out = document.getElementsByClassName('out')[0].outerHTML
console.log(out)
// 結果:<div class="out">out</div>