[英]How to make input appear as sentence case based on typing using angular8
嗨,我有一個輸入字段,根據輸入,我想將文本顯示為句子大小寫,但它顯示為標題大小寫。 如果我輸入"hello hai how are you"
它會顯示為"Hello Hai How Are You"
但我希望它顯示為"Hello hai how are you"
,但如果用戶在輸入時只使用 CapsLock,那么它應該允許優先.
演示:
帶管道的 DEMO2:
HTML:
<div class="col-md-6 mb-3">
<label for="input1">Input Field to be sentense case</label>
<input type="text" class="form-control text-capitalize" id="input1" placeholder="Name"
formControlName="name"
name="name"
required />
</div>
HTML2:
<form [formGroup]="myForm">
<input formControlName="myNumber| titleCase" />
</form>
TS:
this.myForm = this.fb.group({
myNumber: ["hello hai how are you"]
});
管道.ts:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "titleCase" })
export class TitleCasePipe implements PipeTransform {
public transform(input: string): string {
console.log(input);
if (!input) {
return "";
} else {
return input.replace(
/\b((?!=|\,|\.).)+(.)\b/g,
first => first.substr(0, 1).toUpperCase() + first.substr(1)
);
}
}
}
您可以使用.toUpperCase()
和.toLowerCase()
以及.substring()
來實現如下效果:
function turnIntoSentence(){ var input = document.getElementById("input"); input.value=input.value.substring(0,1).toUpperCase()+input.value.substring(1).toLowerCase(); }
<input id="input" type="text" oninput="turnIntoSentence()">
我們可以強制第一個字母大寫,其余字母小寫。
var input = document.getElementById("input"); function turnIntoSentence(){ input.value=input.value.substring(0,1).toUpperCase()+input.value.substring(1).toLowerCase(); } input.addEventListener("keyup", function(event) { if (event.getModifierState("CapsLock")) { input.value=input.value.toUpperCase(); }else{ turnIntoSentence(); } });
<input id="input" type="text" oninput="turnIntoSentence()">
您還可以利用事件偵聽器在啟用大寫鎖定時允許大寫。
如果您有多個輸入字段:
var input = document.getElementsByClassName("input"); function turnIntoSentence(){ for(var i = 0; i < input.length; i++){ input[i].value=input[i].value.substring(0,1).toUpperCase()+input[i].value.substring(1).toLowerCase(); } }
<input class="input" type="text" oninput="turnIntoSentence()"> <input class="input" type="text" oninput="turnIntoSentence()"> <input class="input" type="text" oninput="turnIntoSentence()">
我想你想要這樣的東西:
在你的 html 中:
<input type="text" class="form-control" id="input1" placeholder="Name"
formControlName="name"
name="name"
#name
required
(input)="handleInputChange(name.value)"/>
在你的 ts 中:
handleInputChange(val: string){
val = val.substr(0,1).toUpperCase() + val.substr(1);
this.form.name.setValue(val);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.