[英]Javascript replace one or another
I'm trying to make the replace
function work when having one match or another. 我正在尝试在进行一场比赛或另一场比赛时使用
replace
功能。 It's very simple as a logic so I'd like to have a very simple implementation. 作为逻辑,它非常简单,所以我想有一个非常简单的实现。
I have tried: 我努力了:
var my_url = document.URL;
var tmpl = "?tmpl=component" || "&tmpl=component"; //This is the tricky part
location.href = my_url.replace(tmpl,"");
...but it doesn't seem to work. ...但是似乎无效。 Any ideas please?
有什么想法吗?
This is not how JavaScript works, logical OR is useless here. 这不是JavaScript的工作方式, 逻辑OR在这里没有用。 One possible way is using regex :
一种可能的方法是使用regex :
location.href = my_url.replace(/[?&]tmpl=component/, "");
Here the replace
method will replace any match of tmpl=component
starting with either ?
在这里,
replace
方法将替换任何以?
开头的tmpl=component
匹配项?
or &
. 或
&
。
You could do two replacements: 您可以做两个替换:
location.href = my_url.replace("?tmpl=component", "").replace("&tmpl=component", "");
or you could use a regular expression: (recommended) 或者您可以使用正则表达式:(推荐)
location.href = my_url.replace(/[?&]tmpl=component/, "");
[?&]
will match either a '?' [?&]
将匹配一个'?' or '&' character. 或“&”字符。
You're setting tmpl
to be the value of the expression "?tmpl=component" || "&tmpl=component";
您将
tmpl
设置为表达式"?tmpl=component" || "&tmpl=component";
"?tmpl=component" || "&tmpl=component";
, which will always evaluate to "?tmpl=component"
, since it is the first truthy value in your or statement. ,该值将始终为
"?tmpl=component"
,因为它是or语句中的第一个真实值。
You can do this with regex in a number of ways: 您可以通过多种方式使用正则表达式进行此操作:
my_url.replace(/?tmpl=component|&tmpl=component/, "");
my_url.replace(/[?&]tmpl=component/, "");
最好的是:
var tmpl = (my_url.indexOf("?tmpl=component") > -1)? "?tmpl=component" : "&tmpl=component";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.