11

I have a selectbox with parameters as the value in the option, set like this:

<option value="{$i.tileid}androoftiletypeeq{$i.model}andproducenteq{$i.producent}">{$i.name} {$i.$title}</option>

I am trying to replace all "and" and "eq" to "&" and "=", but I can only get my javascript to replace the first occurrence. The form is named / ID'ed "rooftile_select

$("#rooftile_select").change(function(event) {

  event.preventDefault(); 

  var data = $("#rooftile_select").serialize();                
  var pathname = window.location;
  var finalurl = pathname+'&'+data;

  var replaced = finalurl.replace("and", "&").replace("eq", "=");
});

The last parameters in finalurl then looks like this:

&rid=56&rooftiletype=9andproducenteqs

Am I missing something?

Morten Hagh
  • 2,055
  • 8
  • 34
  • 66
  • possible duplicate of [Javascript multiple replace](http://stackoverflow.com/questions/832257/javascript-multiple-replace) – James Allardice Apr 30 '13 at 10:11
  • This answer might provide a solution: http://stackoverflow.com/questions/1137436/what-are-useful-javascript-methods-that-extends-built-in-objects/1137579#1137579 – Joachim VR Apr 30 '13 at 10:13

4 Answers4

39
var replaced = finalurl.replace(/and/g, '&').replace(/eq/g, '=');

This should do the trick. With the g after the / you're saying that you want to replace all occurences.

Michael Kunst
  • 2,978
  • 25
  • 40
  • This would replace "sand" with "s&" and "equation" with "=uation". Just be aware of that in case you're passing words like that. – dhaupin Aug 11 '16 at 17:03
1

Try this :

replaced = finalurl.replace(/and/g, "&").replace(/eq/g, "=");
Woody
  • 7,578
  • 2
  • 21
  • 25
1

Since ES12

As of August 2020, modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 (ES12) language specification.

var replaced = finalurl.replaceAll('and', '&').replaceAll('eq', '=');

Otherwise

We can do a full replacement only if we supply the pattern as a regular expression

var replaced = finalurl.replace(/and/g, '&').replace(/eq/g, '=');
PaulCrp
  • 624
  • 1
  • 8
  • 19
0

You can use regexp with global flag

var finalurl = '{$i.tileid}androoftiletypeeq{$i.model}andproducenteq{$i.producent}';
finalurl.replace(/and/g, "&").replace(/eq/g, "=")

If your string is always going to contain {...} variables in it, you can use following to avoid accidently replacing the variable or request parameter name

finalurl.replace(/\}and/g, "}&").replace(/eq\{/g, "={")
Ejaz
  • 8,719
  • 3
  • 34
  • 49