Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace() only replaces first match [duplicate]

Hello see the jsfiddle here : http://jsfiddle.net/moolood/jU9QY/

var toto = 'bien_address_1=&bien_cp_1=&bien_ville_1=';
var tata = toto.replace('&','<br/>');
$('#test').append(tata);

Why Jquery in my exemple only found one '&' and replace it?

like image 574
user367864 Avatar asked Jun 18 '13 21:06

user367864


People also ask

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.

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Does string replace replace all occurrences?

The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.


2 Answers

Because that's how replace works in JavaScript. If the search argument is a string, only the first match is replaced.

To do a global replace, you have to use a regular expression with the "global" (g) flag:

var tata = toto.replace(/&/g,'<br/>');
like image 107
T.J. Crowder Avatar answered Nov 26 '22 20:11

T.J. Crowder


The code that you have written will only replace the first instance of the string.

Use Regex along with g will replace all the instances of the string.

toto.replace(/&/g,'<br/>');
like image 21
Sushanth -- Avatar answered Nov 26 '22 20:11

Sushanth --