我想在不使用replace()
方法的情况下使代码更简洁。
写一个函数royalWe(句子)返回一个字符串:
示例:
royalWe("I want to go to the store")
=> "我们想去商店"
royalWe("This is mine")
=> "这是我们的"
royalWe("Jump for my love")
=> "跳跃为我们的爱"
royalWe("This is my house and you will respect me")
=> "这是我们的房子,你会尊重我们的#34;
我的代码:
function royalWe(sentence){
var sent = sentence.split(" ");
var newSent = [];
var replaceWords = ["I","mine","my","me"];
var words = ["we","ours","our","us"]
for(var i = 0; i < sent.length; i++) {
var idxofchar = replaceWords.indexOf(sent[i]);
if(idxofchar !== -1) {
var word = sent[i].split(sent[i]).join(words[idxofchar])
newSent.push(word);
} else {
newSent.push(sent[i]);
}
}
return newSent.join(" ");
}
答案 0 :(得分:0)
使用函数方法而不使用正则表达式,您可能希望将for
循环替换为Array.prototype.map
。您还可以将替换字符串存储为对象中的键值映射,而不是存储在两个并行数组中。
function royalWe(sentence) {
var replacements = { I: "we", mine: "ours", my: "our", me: "us" };
return sentence
.split(" ")
.map(function(word) { return replacements[word] || word; })
.join(" ");
}
console.log(royalWe("I want to go to the store"));
console.log(royalWe("This is my house and you will respect me"));
console.log(royalWe("This is mine"));
console.log(royalWe("Jump for my love"));
如果你使用String.prototype.replace
,它会更有效率,代码也会非常相似。您可以使用的正则表达式为/[a-z]+/gi
,它选择每个字符串中包含1个或多个字符的字符串。
function royalWe(sentence) {
var replacements = { I: "we", mine: "ours", my: "our", me: "us" };
return sentence.replace(/[a-z]+/gi, function(word) {
return replacements[word] || word;
});
}
console.log(royalWe("I want to go to the store"));
console.log(royalWe("This is my house and you will respect me"));
console.log(royalWe("This is mine"));
console.log(royalWe("Jump for my love"));