Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace multiple occurences in a string with javascript

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?

like image 934
Morten Hagh Avatar asked Apr 30 '13 10:04

Morten Hagh


People also ask

How will you replace all occurrences of a string in JavaScript?

The replaceAll() method returns a new string with 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. The original string is left unchanged.

How do I replace multiples in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

Can you replace all occurrences?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')


2 Answers

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.

like image 126
Michael Kunst Avatar answered Sep 19 '22 20:09

Michael Kunst


Try this :

replaced = finalurl.replace(/and/g, "&").replace(/eq/g, "=");
like image 33
Woody Avatar answered Sep 18 '22 20:09

Woody