{"id":150,"date":"2019-09-16T16:57:48","date_gmt":"2019-09-16T16:57:48","guid":{"rendered":"https:\/\/tutorialio.com\/?p=150"},"modified":"2025-11-04T10:31:25","modified_gmt":"2025-11-04T10:31:25","slug":"replace-all-occurrences-of-a-string-in-javascript","status":"publish","type":"post","link":"https:\/\/hellonitish.com\/blog\/replace-all-occurrences-of-a-string-in-javascript\/","title":{"rendered":"Replace all Occurrences of a String in JavaScript"},"content":{"rendered":"<p>JavaScript has a lot of useful methods that you can use to manipulate strings. For example, there is a <code>String.replace()<\/code> method to replace a simple substring with another string. One problem with this method is that it only replaces the first occurrence of the word or substring. In this tutorial, we will learn about different methods which can be used to replace all occurrences of a substring inside the main string.<\/p>\n<h2 id=\"using-regexp-with-the-g-flag-to-replace-all-occurrences-of-a-string\">Using RegExp With the \u2018g\u2019 Flag to Replace all Occurrences of a String<\/h2>\n<p>Since <code>String.replace()<\/code> does not replace all the occurrences of a simple substring inside another string. You can pass the word or substring as a regular expression with the  <code>g<\/code> flag attached to it. This way the string will replace all occurrences of the given word or substring. Here is an example:<\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like apples a lot. You ate all my apples.\";\nvar find = \/apples\/g;\nvar replacement = 'bananas';\nvar result = sentence.replace(find, replacement);\n\n\/\/ Output \u2014 I like bananas a lot. You ate all my bananas.\nconsole.log(result);<\/code><\/pre>\n<p>This regular expression based solution works perfectly if you want to search for all occurrence of a string and replace it with something else. However, there is one important thing that you need to keep in mind. This method will give unexpected results if the <code>find<\/code> string contains a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Regular_Expressions#Using_special_characters\">special regular expression character<\/a>.  Here is an example in which replaces all occurrences of \u201capp|les\u201d inside the main string breaks things. This is because pipe is a special character in regular expressions.<\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like app|les a lot. You ate all my app|les.\";\nvar find = \/app|les\/g;\nvar replacement = 'bananas';\nvar result = sentence.replace(find, replacement);\n\n\/\/ Output \u2014 I like bananas|bananas a lot. You ate all my bananas|bananas.\nconsole.log(result);<\/code><\/pre>\n<p>You can escape the pipe (<code>|<\/code>) character inside the regular expression by using <code>|<\/code>. This will make sure that the replacement is added only once.<\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like app|les a lot. You ate all my app|les.\";\nvar find = \/app\\|les\/g;\nvar replacement = 'bananas';\nvar result = sentence.replace(find, replacement);\n\n\/\/ Output \u2014 I like bananas a lot. You ate all my bananas.\nconsole.log(result);<\/code><\/pre>\n<h2 id=\"using-split-and-join-to-replace-all-occurrences-of-a-string\">Using split() and join() to Replace all Occurrences of a String<\/h2>\n<p>If you want to avoid escaping the special characters that might get passed in the regular expression we used earlier to replace all occurrences of a string, you should consider using the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\/split\">String.split()<\/a> and <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/join\">Array.join()<\/a> methods together.<\/p>\n<p>The <code>String.split()<\/code> method splits the calling string into an array of substrings, using the specified separator string to determine where to make each split. This separator string will be the substring that you want to replace.<\/p>\n<p>The <code>Array.join()<\/code> method joins all the elements of an element together using the specified glue string and returns the combined string. This glue will be the substring that you want to be the replacement of the old substring in the main string.<\/p>\n<p>In the following example, we will use these methods together to replace all occurrences of \u201capples\u201d with \u201cbananas\u201d.<\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like apples a lot. You ate all my apples.\";\nvar find = \"apples\";\nvar replacement = \"bananas\";\nvar result = sentence.split(find).join(replacement);\n\n\/\/ Output \u2014 I like bananas a lot. You ate all my bananas.\nconsole.log(result);<\/code><\/pre>\n<p>With this method, you will no longer have to worry about escaping any special regex characters like you had to in the previous section.<\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like app|les a lot. You ate all my app|les.\";\nvar find = \"app|les\";\nvar replacement = \"bananas\";\nvar result = sentence.split(find).join(replacement);\n\n\/\/ Output \u2014 I like bananas a lot. You ate all my bananas.\nconsole.log(result);<\/code><\/pre>\n<h2 id=\"using-indexof-multiple-times-to-replace-all-occurrences-of-a-string\">Using indexOf() Multiple Times to Replace all Occurrences of a String<\/h2>\n<p>The <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\/indexOf\">String.indexOf()<\/a> method returns the index of the given substring within the calling string. This means that if the main string contains multiple occurrences of a substring, you can just keep calling <code>String.replace()<\/code> until the <code>String.indexOf()<\/code> method finally returns -1. <\/p>\n<p class=\"lang-name\">JavaScript<\/p>\n<pre><code class=\"language-js\">var sentence = \"I like apples a lot. You ate all my apples.\";\nvar find = \"apples\";\nvar replacement = \"bananas\";\n\nvar result = sentence;\nwhile (result.indexOf(find) &gt; -1) {\n    result = result.replace(find, replacement);\n}\n\n\/\/ Output \u2014 I like bananas a lot. You ate all my bananas.\nconsole.log(result);<\/code><\/pre>\n<p>One major problem with this solution is that you can get stuck in an infinite loop if the <code>find<\/code> string can be found inside the <code>replacement<\/code> string. For example, if you were to use this method to replace \u201capples\u201d with \u201cpineapples\u201d, this technique will trigger an infinite loop. This is because the method will keep returning an index greater than -1 when we search for \u201capples\u201d  as \u201cpineapples\u201d also contains \u201capples\u201d.<\/p>\n<h2 id=\"quick-summary\">Quick Summary<\/h2>\n<p>Let&#8217;s recap everything that we have covered in this tutorial.<\/p>\n<ol id=\"summary-points\">\n<li>In order to replace all occurrences of a word in a string, you can simply use the inbuilt <code>String.replace()<\/code> method and provide the string you want to replace as a regex expression with the <code>g<\/code> flag. The only problem with this solution is that you will have to escape all the special characters in the <code>find<\/code> string that you want to replace.<\/li>\n<li>If you don\u2019t want to deal with special regex characters, you can also use the <code>String.split()<\/code> and <code>Array.join()<\/code> methods togehter to break the string using one substring and then joining it together using another substring.<\/li>\n<li>If you want to use the <code>String.replace()<\/code> method to do the replacements but don\u2019t want to use regex, you can just keep checking the existence of the subtring that you want to replace in the main string using the <code>String.indexOf()<\/code> method. This will generally work fine but you will be stuck in an infinite loop if the <code>replacement<\/code> string contains the <code>find<\/code> string.<\/li>\n<\/ol>\n<p>Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to replace all occurrences of a string in JavaScript. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>JavaScript has a lot of useful methods that you can use to manipulate strings. For example, there is a String.replace() method to replace a simple substring with another string. One problem with this method is that it only replaces the first occurrence of the word or substring. In this tutorial, we will learn about different [&hellip;]<\/p>\n","protected":false},"author":140,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[19,17],"class_list":["post-150","post","type-post","status-publish","format-standard","hentry","category-how-to-guides","tag-javascript","tag-strings"],"_links":{"self":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/150","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/users\/140"}],"replies":[{"embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/comments?post=150"}],"version-history":[{"count":1,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/150\/revisions"}],"predecessor-version":[{"id":10230,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/150\/revisions\/10230"}],"wp:attachment":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/media?parent=150"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/categories?post=150"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/tags?post=150"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}