> let fullInteger = '';
const sentenceText = 'junayed';
for (let i = 0; i < sentenceText.length; i++) {
if (sentenceText[i] == 'n' & sentenceText[i + 1] == 'a') {
let newChar = sentenceText[i]
newChar = 'a';
fullInteger = fullInteger + newChar;
}
else if (sentenceText[i] == 'a' & sentenceText[i - 1] == 'n') {
let newChar = sentenceText[i]
newChar = 'n';
fullInteger = fullInteger + newChar;
}
else{
fullInteger = fullInteger + sentenceText[i];
}
}
console.log(fullInteger);
如果找到“ na”到“ an”,它将采用一个字符串并将其更改。你们中有人知道我该如何缩短它,或者有其他选择吗?
答案 0 :(得分:1)
这应该是一个简单的替换
const sentenceText = 'junayed';
const sentenceText1 = 'junyed';
function replaceContent(sentence){
return sentence.replace(/na/g,'an');
}
console.log(replaceContent(sentenceText));// gives "juanyed" - ie: 'na' has been replaced by 'an'
console.log(replaceContent(sentenceText1));// gives junyed - ie: no 'na' to be replaced
答案 1 :(得分:1)
有很多方法可以实现这一目标。首先让我们尝试使用您的算法:
改进:
&&
而非&
:&
表示按位与,双精度&&
表示逻辑与。i-1
和i+1
上的错误:如果字符串以a
开头或以n
结尾,则代码将中断。您应该为其添加支票。您可以这样:!!sentanceText[index]
其他建议
let newChar = sentenceText[i]
newChar = 'a';
[i] === 'n' && [i+1] === 'a'
,因此只需设置newChar = 'an'
并跳过下一个迭代即可。您可以通过增加i
if (sentenceText[i] == 'n' && sentenceText[i + 1] == 'a') {
fullInteger = fullInteger + 'an';
i++;
}
以下为示例
function getProcessedStr(sentenceText) {
let fullInteger = '';
for (let i = 0; i < sentenceText.length; i++) {
if (sentenceText[i] === 'n' && !!sentenceText[i + 1] && sentenceText[i + 1] === 'a') {
fullInteger = fullInteger + 'an';
i++
} else {
fullInteger = fullInteger + sentenceText[i];
}
}
console.log(fullInteger);
return fullInteger
}
getProcessedStr('junayed');
getProcessedStr('junayedn');