英文:
How to make only one letter in string uppercase?NOT the first one in JS
问题
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;
}
it making uppercase all the string.
Preferred to use upperCase & lowerCase, due to exercise terms. Not necessarily though.
英文:
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;
}
//
it making uppercase all the string.
Preferred to use upperCase & lowerCase,due to exercise terms. Not necceserily though.
//
答案1
得分: 1
由于你不需要更改整个字符串,你可以使用 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'));
请告诉我这是否有所帮助。
英文:
Since you don't need to change the entire string, you can replace the only letter that you need to replace using replace
function.
By default, replace
function only replaces the first occurrence of the string specified as a first parameter. Looks like this is exactly what you are looking for.
This can be achieved like so:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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'));
<!-- end snippet -->
Please let me know if this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论