Make only one letter in string uppercase?不是JS中的第一个。

huangapple go评论58阅读模式
英文:

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 = &#39;a&#39;;
  const A = &#39;A&#39;;
  if (text.includes(A)) return text.replace(A, a);
  if (text.includes(a)) return text.replace(a, A);
  return text;
}

console.log(checkA(&#39;stack stack&#39;));
console.log(checkA(&#39;stAck stAck&#39;));

<!-- end snippet -->

Please let me know if this helps.

huangapple
  • 本文由 发表于 2023年5月14日 21:42:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定