JavaScript - Replace Word of a Sentence



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



  • The first argument is the sentence to perform the search and replace on.

  • The second argument is the word that you will be replacing(before).

  • The 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".



Solution 1 Basic approach


function myReplace(str, before, after) {
    // Find index where before is on string
    var index = str.indexOf(before);
    // Check to see if the first letter is uppercase or not
    if (str[index] === str[index].toUpperCase()) {
        // Change the after word to be capitalized before we use it.
        after = after.charAt(0).toUpperCase() + after.slice(1);
    }
    // Now replace the original str with the edited one.
    return str.replace(before, after);
}
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

Output:


A quick brown fox leaped over the lazy dog

Solution 2 Regex approach


function myReplace(str, before, after) {
    // Check if first character of argument "before" is a capital or lowercase letter and change the first character of argument "after" to match the case
    if (/^[A-Z]/.test(before)) {
        after = after[0].toUpperCase() + after.substring(1)
    } else {
        after = after[0].toLowerCase() + after.substring(1)
    }

    // return string with argument "before" replaced by argument "after" (with correct case)
    return str.replace(before, after);
}
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

Output:


A quick brown fox leaped over the lazy dog

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube