How can I replace every instance of a string in JavaScript

0 votes
In the JS interview, I was facing an issue related to an instance of a string, so can you tell me How I can replace every instance of a string in JavaScript?
Jan 9 in Java-Script by Ashutosh
• 14,020 points
41 views

1 answer to this question.

0 votes

In JavaScript, replacing all instances of a substring within a string can be achieved using several methods:

1. Using String.prototype.replaceAll():

const originalString = 'Hello world! Hello universe!';

const newString = originalString.replaceAll('Hello', 'Hi');

console.log(newString); // Output: 'Hi world! Hi universe!'

Note: replaceAll() is part of ECMAScript 2021 and may not be supported in all environments. Ensure compatibility or consider using a polyfill if targeting older environments.

2. Using String.prototype.replace() with a Global Regular Expression:

const originalString = 'Hello world! Hello universe!';

const newString = originalString.replace(/Hello/g, 'Hi');

console.log(newString); // Output: 'Hi world! Hi universe!'

In this example, the regular expression /Hello/g matches all occurrences of 'Hello'. The replace() method then replaces each match with 'Hi'.

answered Jan 10 by Navya

Related Questions In Java-Script

0 votes
1 answer

How do I break a string across more than one line of code in JavaScript?

Hello @kartik, In your example, you can break ...READ MORE

answered Oct 8, 2020 in Java-Script by Niroj
• 82,840 points
712 views
0 votes
0 answers
0 votes
0 answers
0 votes
1 answer

How can I get query string values in JavaScript?

Hello @kartik, You don't need jQuery for that ...READ MORE

answered Jul 27, 2020 in Java-Script by Niroj
• 82,840 points
1,454 views
0 votes
1 answer
0 votes
1 answer

How can I configure lazy loading for Angular modules?

To configure lazy loading in Angular, you ...READ MORE

answered Dec 12, 2024 in Angular by Navya
56 views
0 votes
1 answer
0 votes
1 answer

How do I delete a specific element from an array in JavaScript?

You can use the splice() method. Code: let arr ...READ MORE

answered Jan 10 in Java-Script by Navya
41 views
0 votes
1 answer

How to include a JavaScript file in another JavaScript file?

Let's assume you have two files: math.js: This ...READ MORE

answered Nov 27, 2024 in Java-Script by kavya
64 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP