【发布时间】:2017-01-14 19:18:46
【问题描述】:
我正在编写一个程序,它采用三个参数,例如,sentence、wordtoreplace、toReplaceWith。
程序应该返回带有wordtoreplace的句子字符串应该用toReplaceWith替换。如果 wordtoreplace 是一个大写的单词,那么被替换的世界也应该大写。我尝试了很多次,但我的代码不起作用。请帮忙。
function myReplace(str, before, after) {
var words = str.split(" ");
var indexOfWord = words.indexOf(before);
if ( before.charAt(0) === before.charAt(0).toUpperCase ) {
after = capitalize(after);
}
str = str.replace(new RegExp(before), after);
function capitalize( word ) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return str.replace(new RegExp(after, 'i', 'g'), after);;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
【问题讨论】:
-
为什么要将字符串拆分成单词?请注意,
RegExp不接受三个参数。你需要用括号调用toUpperCase()。 words 或 indexOfWord 一旦被初始化就不要使用它们。你为什么拥有它们?但是当你的函数的调用者可以很容易地提供大写字母时,应用大写似乎有点多余?它使该功能对用户不友好。
标签: javascript arrays string replace charat