Search and Replace (FreeCodeCamp intermediate algorithm scripting)











up vote
2
down vote

favorite












I completed the challenge and passed the tests:




Perform a search and replace on the sentence using the arguments provided and return the new sentence.



First argument is the sentence to perform the search and replace on.



Second argument is the word that you will be replacing (before).



Third argument is what you will be replacing the second argument with (after).



Note



Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".



Example



myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".




I was hoping to simplify my code more. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?






function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));












share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • How is "cleaner" defined and "faster" measured?
    – guest271314
    2 days ago















up vote
2
down vote

favorite












I completed the challenge and passed the tests:




Perform a search and replace on the sentence using the arguments provided and return the new sentence.



First argument is the sentence to perform the search and replace on.



Second argument is the word that you will be replacing (before).



Third argument is what you will be replacing the second argument with (after).



Note



Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".



Example



myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".




I was hoping to simplify my code more. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?






function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));












share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • How is "cleaner" defined and "faster" measured?
    – guest271314
    2 days ago













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I completed the challenge and passed the tests:




Perform a search and replace on the sentence using the arguments provided and return the new sentence.



First argument is the sentence to perform the search and replace on.



Second argument is the word that you will be replacing (before).



Third argument is what you will be replacing the second argument with (after).



Note



Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".



Example



myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".




I was hoping to simplify my code more. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?






function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));












share|improve this question















I completed the challenge and passed the tests:




Perform a search and replace on the sentence using the arguments provided and return the new sentence.



First argument is the sentence to perform the search and replace on.



Second argument is the word that you will be replacing (before).



Third argument is what you will be replacing the second argument with (after).



Note



Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".



Example



myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".




I was hoping to simplify my code more. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?






function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));








function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));





function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));






javascript performance strings programming-challenge






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 2 at 21:11









200_success

127k15148412




127k15148412










asked Aug 2 at 4:08









Leda Erlandson

111




111





bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • How is "cleaner" defined and "faster" measured?
    – guest271314
    2 days ago


















  • How is "cleaner" defined and "faster" measured?
    – guest271314
    2 days ago
















How is "cleaner" defined and "faster" measured?
– guest271314
2 days ago




How is "cleaner" defined and "faster" measured?
– guest271314
2 days ago










1 Answer
1






active

oldest

votes

















up vote
0
down vote













This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...



Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.



Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.






function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))








share|improve this answer



















  • 2




    The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
    – 200_success
    Aug 2 at 21:22













Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200787%2fsearch-and-replace-freecodecamp-intermediate-algorithm-scripting%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...



Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.



Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.






function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))








share|improve this answer



















  • 2




    The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
    – 200_success
    Aug 2 at 21:22

















up vote
0
down vote













This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...



Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.



Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.






function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))








share|improve this answer



















  • 2




    The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
    – 200_success
    Aug 2 at 21:22















up vote
0
down vote










up vote
0
down vote









This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...



Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.



Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.






function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))








share|improve this answer














This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...



Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.



Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.






function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))








function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))





function myReplace(str, before, after) {
return str.replace(new RegExp(before, 'g'), match => {
return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
})
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))






share|improve this answer














share|improve this answer



share|improve this answer








edited Aug 2 at 21:07

























answered Aug 2 at 21:00









Joseph

22.4k21835




22.4k21835








  • 2




    The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
    – 200_success
    Aug 2 at 21:22
















  • 2




    The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
    – 200_success
    Aug 2 at 21:22










2




2




The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
– 200_success
Aug 2 at 21:22






The regexp should be escaped and case-insensitive. Since the challenge specifies that before is a "word", it should also have b assertions at the beginning and end.
– 200_success
Aug 2 at 21:22




















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200787%2fsearch-and-replace-freecodecamp-intermediate-algorithm-scripting%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Ellipse (mathématiques)

Quarter-circle Tiles

Mont Emei