jQuery 用javascript替换字符串中的多次出现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16297320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace multiple occurences in a string with javascript
提问by Morten Hagh
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
我试图将所有“and”和“eq”替换为“&”和“=”,但我只能让我的javascript替换第一次出现。表单被命名为/ID 为“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?
我错过了什么吗?
回答by Michael Kunst
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
after/
你是说你想替换所有出现的。
回答by Ejaz
You can use regexp with globalflag
您可以使用带有全局标志的正则 表达式
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, "={")
回答by Woody
Try this :
尝试这个 :
replaced = finalurl.replace(/and/g, "&").replace(/eq/g, "=");