簡體   English   中英

如何將一半的srting用大寫,另一半用小寫?

[英]how to make half of the srting in uppercase and the other half in lowercase?

我試圖編寫一個代碼,將句子的一半變成大寫,另一半變成小寫,但它不起作用。 需要幫助,這是我的代碼。

const fullClintStr = prompt("please enter text: ");
const strlen = fullClintStr.length;
const lowerCaseStr = fullClintStr.toLowerCase();
const upperCaseStr = fullClintStr.toUpperCase();
const MiddleSentence = (strlen/2).toFixed(0);

for (let i = 0; i < MiddleSentence; i++) {
    
    var finalSTR = upperCaseStr[i].toUpperCase(upperCaseStr[i]);
    
    
}
window.alert(finalSTR);

您可以使用slice方法來獲取您想要的內容,而不是循環遍歷。 此外,您的循環不起作用,因為您的finalStr被重新分配了最新的字符。

再次肯定有一個 scope 來防止整個字符串的小寫大寫,而是只對left and right substrings執行這些操作,並將它們都添加到 @Tim 所做的finalStr中。

 const fullClintStr = prompt("please enter text: "); const strlen = fullClintStr.length; const lowerCaseStr = fullClintStr.toLowerCase(); const upperCaseStr = fullClintStr.toUpperCase(); const MiddleSentence = (strlen/2).toFixed(0); let finalSTR = lowerCaseStr.slice(0,MiddleSentence) + upperCaseStr.slice(MiddleSentence, strlen); window.alert(finalSTR);

我會在這里使用substring

 var fullClintStr = "javascript"; var strlen = fullClintStr.length; var output = fullClintStr.substring(0, strlen/2).toLowerCase() + fullClintStr.substring(strlen/2).toUpperCase(); console.log(output);

你可以做這樣的事情。

 const fullClintStr = prompt("please enter text: "); const firstHalf = fullClintStr.substring(0, fullClintStr.length / 2).toUpperCase(); const secondHalf = fullClintStr.substring((fullClintStr.length / 2), fullClintStr.length).toLowerCase(); const finalText = `${firstHalf}${secondHalf}` console.log(finalText)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM