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
• 20,870 points
110 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
776 views
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,523 views
0 votes
1 answer

How can I determine the type of an HTML element in JavaScript?

Hello @kartik, nodeName is the attribute you are looking ...READ MORE

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

How do I search for a key of object in javascript?

Use hasOwnProperty(key) for (let i = 0; i ...READ MORE

answered Oct 14, 2020 in Java-Script by Niroj
• 82,840 points
2,645 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
116 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How can I determine if a string begins with another string in JavaScript?

You can use the startsWith() method. Syntax: string.startsWith(searchString, position) Example: const ...READ MORE

answered Feb 7 in Java-Script by Navya
91 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