[英]javascript regular expression optional character
I want to replace url parameters by using regular expression. 我想使用正则表达式替换url参数。
My code : 我的代码:
query = window.location.search;
query.replace(new RegExp(query.match('f=(.*)&?')[1],'g'),'2');
But there is possible two situation, 但是可能有两种情况,
first: 第一:
query can be "?f=23" 查询可以是“?f = 23”
second: 第二:
query can be "?f=23&id=1", 查询可以是“?f = 23&id = 1”,
my code work for first situation , but it doesn't work for second situation. 我的代码适用于第一种情况,但不适用于第二种情况。
How can I replace my query for both situation ? 如何针对这两种情况替换查询?
function control(parameter,value) {
var newUrl;
var url = window.location.href.split('?')[0];
var query = window.location.search;
var check = query.indexOf('f');
if (check == -1) {
var qCheck = query.indexOf('?');
if (qCheck == -1) {
query = query+'?'+parameter+'='+value;
} else {
query = query+'&'+parameter+'='+value;
}
} else {
var c = query.indexOf('&');
if(c == -1) {
query = query.replace(new RegExp(query.match(parameter+'=(.*)')[1],'g'),value);
} else {
query = query.replace(new RegExp(query.match('f=(.*)&')[1],'g'),value);
}
}
history.pushState(null,null,url+query);
}
From what I understand, you want to replace the parameter f
with the value 2, therefore: 据我了解,您想将参数
f
替换为值2,因此:
query = window.location.search;
query = query.replace( /f=(.*?)&?/g, 'f=2' );
the .*?
.*?
makes the match non-greedy. 使匹配不贪心。
Here is what you want: 这是您想要的:
query = window.location.search; // "?f=23&id=1"
query.replace( /(f=).*(&)/, '$1'+ '2' +'$2' );
> "?f=2&id=1"
query.replace( /(f=).*(&)/, '$1'+ 'something' +'$2' );
> "?f=something&id=1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.