[英]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.我正在尝试将所有“and”和“eq”替换为“&”和“=”,但我只能让我的 javascript 替换第一次出现。 The form is named / ID'ed "rooftile_select该表单被命名/标识为“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: finalurl 中的最后一个参数如下所示:
&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. 在/
后面加g
表示您要替换所有出现的情况。
You can use regexp with global flag 您可以将regexp与全局标志一起使用
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, "=");
As of August 2020, modern browsers have support for the String.replaceAll()
method defined by the ECMAScript 2021 ( ES12 ) language specification.截至 2020 年 8 月,现代浏览器支持由 ECMAScript 2021 ( ES12 ) 语言规范定义的String.replaceAll()
方法。
var replaced = finalurl.replaceAll('and', '&').replaceAll('eq', '=');
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, '=');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.