JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  1. 05-Arrays
  2. Array Methods

.replace() Method

Use the .replace() method to search for a certain string and replace it with another. Take this sentence for example: "Your baby is going to be awesome regardless of it's gender." The sentence is incorrect; it uses the contraction it's (it is) rather than the possessive its. We can fix that using the .replace() method.

var wrong = "Your baby is going to be awesome regardless of it's gender.";

//replace it's with its
var notWrong = wrong.replace("it's", "its");

console.log(notWrong);

Output

`Your baby is going to be awesome regardless of its gender.`

The one important thing to note is that the .replace() method is set up like so:

.replace("old", "new");

The first argument is what you want to replace and the second argument is what you want to replace it with.

By adding g for global and i for case insensitive, you can replace any instance of a string, regardless of whether it is upper or lowercase.

var str = "I have experience with HTML, C#, and javascript. Javascript is the language I enjoy the most.";

//search for any instance of "javascript" and replace it with "JavaScript"
var strNew = str.replace(/javascript/gi, "JavaScript");

console.log(strNew);

Output

`I have experience with HTML, C#, and JavaScript. JavaScript is the language I enjoy the most.`
Previous.split() MethodNext.splice() Method

Last updated 7 years ago