replace multiple occurences in a string with javascript

32,649

Solution 1

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.

Solution 2

Try this :

replaced = finalurl.replace(/and/g, "&").replace(/eq/g, "=");
Share:
32,649
Morten Hagh
Author by

Morten Hagh

Updated on July 09, 2022

Comments

  • Morten Hagh
    Morten Hagh almost 2 years

    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?