Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace function only works once (javascript)

I need to replace a string (str1) with another string (str2) every time str1 shows in a specific div.

This is what I got so far

<script type="text/javascript"> 
$(window).load(function(){

var str=document.getElementById("foo").innerHTML; 
var n=str.replace("Google","Yahoo");
document.getElementById("foo").innerHTML=n;

}); 

</script>

and the html

<div id="foo">
Google is the best website ever <br />
Google is not the best website ever</div>

Unfortunately, when I run it, it only replaces the first instance of the word Google.

What am I doing wrong? What do I need to add to make it replace ALL the instances of the word?

like image 568
Yes I am a cat Avatar asked Mar 27 '13 11:03

Yes I am a cat


People also ask

How does the Replace function work in JavaScript?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

Does replace replace all occurrences?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

Is replace () a function?

What is the REPLACE Function? The REPLACE Function[1] is categorized under Excel TEXT functions. The function will replace part of a text string, based on the number of characters you specify, with a different text string.

What is the use of replace () method?

The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.


1 Answers

Use regex /string/g to replace all occurrences, you are using substring which will replace only first occurances as per documentation of replace() function.

Live Demo

var n=str.replace(/Google/g,"Yahoo");

String.prototype.replace() The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

str.replace(regexp|substr, newSubStr|function)

You are using substr pattern which will replace first occurance only.

substr (pattern)

A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.

Use this regexp patter to replace all occurances.

regexp (pattern)

A RegExp object or literal. The match is replaced by the return value of parameter #2.

like image 80
Adil Avatar answered Oct 06 '22 08:10

Adil