本文內容
1、控制太輸出帶有顏色的信息
2、字符串去除前、后空格
3、文本框只能輸入數字
4、密碼強度實時驗證
5、字符串敏感詞過濾
6、圖片放大鏡效果
一、控制太輸出帶有顏色的信息
/*輸出帶有顏色的log*/
log(des: 描述信息, value: 需要高亮顯示的值){
console.log("%c%s",
"color: red; background: yellow; font-size: 24px;",
value,'(',des,')');
}
click(){
this.log('輸出的信息為:','高亮值!');
}
二、字符串去除前、后空格
const str = ' bcdefg ';
const str1 = str.replace(/(^\s*)|(\s*$)/g, '');
this.log('去除字符串前后的空格',str1);
const str2 = str.replace(/(^\s*)/g,"");
this.log('去除字符串前面的空格',str2);
const str3 = str.replace(/(\s*$)/g,"");
this.log('去除字符串后面的空格',str3);
二
三、文本框只能輸入數字
<TextInput style={styles.textInputStyle}
value={this.state.textInputNumber}
placeholder={'只能輸出數字'}
onChangeText={(text)=>{
this.setState({
textInputNumber: text.replace(/\D/g, ''),
})
}}
/>
四、密碼強度實時驗證
字母、數字、特殊符號都有固定的權重,遍歷密碼字符串,得到總得權重的值,根據權重的范圍判斷密碼的強弱
/*計算字符權重*/
charStrength(char){
//字符的 ASCII 碼
if (char >= 48 && char <= 57){ // 數字
return 1;
}
if (char >= 97 && char <= 122){ // 小寫字母
return 2;
}
return 3; // 其他字符
}
/*密碼強度檢查*/
passwordStrength(text){
/*
* 字符權重
* 數字 1、字母 2、其他字符 3 (更具體的可以分為大寫、小寫字母的權重,此處將字符串轉成小寫,判斷權重)
* 當密碼長度小于6時,不符合標準
* 長度>=6,強度<10,強度:弱
* 長度>6,強度>=10 且 強度<15,強度:中
* 長度>6,強度>=15,強度:強
* */
const strength = ['密碼太短', '弱', '中', '強'];
const color = ['red', 'puple', 'orange', 'green'];
if (text.length < 6){
this.setState({
psdStrength: strength[0],
psdStrengthColor: color[0],
})
}else {
let strStrength = 0;
for (let i = 0; i < text.length; i++){
strStrength += this.charStrength(text.toLocaleLowerCase().charCodeAt(i)); // 遍歷字符串,轉成小寫,轉成ASCII
}
this.log('強度',strStrength);
if (strStrength < 10){
this.setState({
psdStrength: strength[1],
psdStrengthColor: color[1],
})
}else if(strStrength >= 10 && strStrength < 15){
this.setState({
psdStrength: strength[2],
psdStrengthColor: color[3],
})
}else {
this.setState({
psdStrength: strength[3],
psdStrengthColor: color[3],
})
}
}
}
<View style={{flexDirection: 'row'}}>
<TextInput style
![Uploading 1C340D38-CBDF-443A-A934-A15A5AAEE091_558131.png . . .]={styles.textInputStyle}
value={this.state.textInputPsd}
placeholder={'請輸入密碼'}
onChangeText={(text)=>{
this.passwordStrength(text);
this.setState({
textInputPsd: text,
})
}}
/>
<Text style={[styles.textInputStyle, {lineHeight: 30, backgroundColor: 'transparent', color: this.state.psdStrengthColor}]}>
{this.state.psdStrength}
</Text>
</View>
1C340D38-CBDF-443A-A934-A15A5AAEE091.png
五、字符串敏感詞過濾
根據敏感詞的數組,循環,進行字符串的替換,將敏感詞匯替換成***
const keyWords = ['外掛', '性感', '色情', '爆炸', '死'];
let string = '大家好,我很喜歡玩游戲,但是碰到很多人使用外掛,就不喜歡玩了,我還喜歡美女,特別是性感的美女,昨天上午發生爆炸了,好多人都死了,好恐怖';
for (let i = 0; i < keyWords.length; i++) {
string = string.replace(keyWords[i],'***');
}
this.log('過濾后的字符串',string);
4208C5A5-5C53-41FD-B2BC-89CCA822C975.png
六、圖片放大鏡效果
淘寶網為了讓買家更加了解產品的細節,當買家將鼠標指針移動到產品圖片上時,會有一個局部放大的效果。
本質是:一張小圖一張等比例的大圖,當鼠標在小圖上移動時,計算出對應的大圖應該顯示的位置及寬、高
放大鏡的大小為100 x 100
小圖的大小為400 x 400
大圖的大小為2000 x 2000,
大圖的容器大小為1000 x 1000
例如:
放大鏡的位置在 {0,0,100,100}
這大圖顯示的位置{0、0、500、500}
放大鏡的位置在 {50,80,100,100}
這大圖顯示的位置{250、4000、500、500}
小圖等比例放大5倍后的位置,就是大圖要顯示的位置