[英]Reverse case (Lowercase/Uppercase) of an input value character by character
通過使用一個輸入文本框並且輸入類型只允許使用字母。輸入的值是“a”,它應該在文本框外顯示為“A”嗎?
如果我們在輸入文本中輸入字母小“a”,那么它會希望在框的外部顯示大寫“A”......以下是我的 html 代碼:
<!DOCTYPE html>
<html>
<head>
<!--<script type="text/javascript" href="check.js"></script>-->
</head>
<body>
<input type="text">
<script>
function myFunction()
{
var A = document.getElementById('input').value;
console.log('alphabet'.toUpperCase());
}
</script>
</body>
</html>
要顯示大小寫反轉的輸入值,您應該:
在輸入的onkeyup
事件中調用您的函數,以使用輸入的字符串立即更新預覽。
並循環遍歷您的字符串,並為每個字符測試它是否為uppercase
,將其反轉為lowercase
lowercase
其設為uppercase
。
這是一個片段演示:
function myFunction() { var A = document.getElementById('input').value; var output = ''; for (var i = 0, len = A.length; i < len; i++) { var character = A[i]; if (character == character.toLowerCase()) { // The character is lowercase output = output + character.toUpperCase(); } else { // The character is uppercase output = output + character.toLowerCase(); } } document.getElementById("preview").innerText = output; }
<input id="input" type="text" pattern="[A-Za-z]" onkeyup="myFunction()" /><span id="preview"></span>
您可以在編寫時使用事件立即更新結果。
document.getElementById('input').addEventListener('keyup', function () { var input = document.getElementById('input').value; if (!input.match(/^[az]*$/i)) { document.getElementById('output').innerHTML = 'Wrong input'; return; } document.getElementById('output').innerHTML = input.split('').map(function (a) { return a.match(/[az]/) ? a.toUpperCase() : a.toLowerCase(); }).join(''); });
<input type="text" id="input"> <div id="output"></div>
function reverseCase(str) {
let newstr = str.split('');
let newarr = [];
//return newstr;
for(i=0; i<newstr.length; i++) {
if(newstr[i] == newstr[i].toLowerCase()){
newarr.push(newstr[i].toUpperCase());
}else
if(newstr[i] == newstr[i].toUpperCase()){
newarr.push(newstr[i].toLowerCase());
}
} return newarr.join('');
}
console.log(reverseCase("Happy Birthday"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.