简体   繁体   中英

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?

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.

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, "={")

尝试这个 :

replaced = finalurl.replace(/and/g, "&").replace(/eq/g, "=");

With 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, '=');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM