Switching words in a string using replace

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:

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:

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:

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

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe