function checkA(string1) {
let a = "a";
let A = "A";
let text = string1;
if (text.includes(A)) {
return text.toLowerCase(A);
} else if (text.includes(a)) {
return text.toUpperCase(a);
} else {
return text;
}
}
function writeWord() {
let inputWord = document.getElementById("anyWord").value;
let checkedWord = checkA(inputWord);
document.getElementById("someString").innerHTML = checkedWord;
}
// 它使所有字符串大写。 由于练习条款,首选使用大写和小写。不过不一定。 //
由于不需要更改整个字符串,因此可以使用
replace
函数替换唯一需要替换的字母。
默认情况下,
replace
函数仅替换指定为第一个参数的字符串的第一次出现。看起来这正是您要找的东西。
可以这样实现:
function checkA(text) {
const a = 'a';
const A = 'A';
if (text.includes(A)) return text.replace(A, a);
if (text.includes(a)) return text.replace(a, A);
return text;
}
console.log(checkA('stack stack'));
console.log(checkA('stAck stAck'));
如果有帮助,请告诉我。