我有一个句子,我必须用另一个单词替换每个单词,并且该单词可以比它替换的单词更长/更短,因此它与问题相似,但它们不是固定长度,而是动态的。
我的解决方案
为简单起见,我只关注一个词。
const oldWord = "tEsT";
const newWord = "testing";
拆分两个单词,以便我可以遍历每个单独的字母。
const oldWordLetters = oldWord.split("");
const newWordLetters = newWord.split("");
现在,我将遍历这些newWord
字母并使用它的索引来获取oldWord
相同位置的相应字母。然后我会检查旧字母是否大写,如果是,则将新字母也放在相同的位置大写。
for (const [i, letter] of newWordLetters.entries()) {
const oldLetter = oldWordLetters[i];
// stop iterating if oldWord is shorter (not enough letters to copy case).
if (!oldLetter) {
break;
}
const isCapital = oldLetter === oldLetter.toUpperCase();
// make the new letter in the same position as the old letter capital
if (isCapital) {
newWordLetters[i] = letter.toUpperCase();
}
}
最终的世界将是tEsTing
在再次加入字母之后。
const finalWord = newWordLetters.join("");
console.log(finalWord); // "tEsTing"
完整代码
const oldWord = "tEsT";
const newWord = "testing";
const oldWordLetters = oldWord.split("");
const newWordLetters = newWord.split("");
for (const [i, letter] of newWordLetters.entries()) {
const oldLetter = oldWordLetters[i];
// stop iterating if oldWord is shorter (not enough letters to copy case).
if (!oldLetter) {
break;
}
const isCapital = oldLetter === oldLetter.toUpperCase();
// make the new letter in the same position as the old letter capital
if (isCapital) {
newWordLetters[i] = letter.toUpperCase();
}
}
const finalWord = newWordLetters.join("");
console.log(finalWord);