Skip to content
the poor coder

Switching words in a string using replace

Poor Man
Published
Reading time
1 min read
On this page

Switching words in a string using replace#

If you need to switch one word with another in a given string, you can use the replace() method in JavaScript. The replace() method will search for a specified value in a string and replace it with another value.

Example:#

Text
let myString = "Hello World";
let newString = myString.replace("World", "Universe");
console.log(newString); // Output: "Hello Universe"

In the above example, we have declared a string "Hello World" and then used the replace() method to switch "World" with "Universe". The output will be "Hello Universe".

Multiple Replacements:#

If you need to switch multiple words in a given string, you can chain the replace() method. For example:

Text
let myString = "I love JavaScript";
let newString = myString.replace("JavaScript", "coding").replace("love", "enjoy");
console.log(newString); // Output: "I enjoy coding"

In the above example, we have switched "JavaScript" with "coding" and "love" with "enjoy". The output will be "I enjoy coding".

Using Regular Expressions:#

If you need to switch all occurrences of a word in a given string, you can use regular expressions. For example:

Text
let myString = "JavaScript is a great language, JavaScript is easy to learn";
let newString = myString.replace(/JavaScript/g, "Python");
console.log(newString); // Output: "Python is a great language, Python is easy to learn"

In the above example, we have used a regular expression to replace all occurrences of "JavaScript" with "Python". The output will be "Python is a great language, Python is easy to learn".

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC