我“有”这种模式,但它没有完全给我我需要的东西,虽然它有效。
var regex = new RegExp('\\b' + data.keyword + '(=[^&]*)?(&|$)',"gi");
但是下面的正则表达式“是”我需要的东西,但我似乎无法让它在正则表达式obj中工作: /&安培; dyanmicTxtHere(\ = [^&安培;] )(=安培; |?$)|?^ dyanmicTxtHere(\ = [^&安培;] )(&安培; | $)?/ < / p>
我试过:这不起作用 -
var regex = new RegExp('&' + data.keyword + '(=[^&]*)?|^' + data.keyword + '(=[^&]*)?&?',"gi");
我无法弄清楚原因。所以上面的正则表达式应该删除我传递的param(和vlaue)(data.keyword),并处理?和&amp;无论那个参数放在网址中的哪个地方。它
那么,这会匹配什么?
www.someurl.com?Keyword=foo
www.someurl.com?up=down&Keyword=foo
www.somurl.com?up=down&keyword=foo&left=right
等......所以,如果我将“关键字”作为我的动态参数传递,那么它将删除它及其相关值。
答案 0 :(得分:3)
在我看来,你想要的是通过JavaScript从请求中读取参数值,对吗?
尝试使用:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
答案 1 :(得分:1)
如果您需要查看生成的正则表达式的外观,只需致电regex.toString()
如果你在试过的那个上做到了:
/&dyanmicTxtHere(=[^&]*)?|^dyanmicTxtHere(=[^&]*)?&?/gi
基于此,您可以公平地看到需要更改的内容,使其像您提供的正则表达式一样:
var regex = new RegExp('&' + data.keyword + '(\\=[^&])?(?=&|$)|^' + data.keyword + '(\\=[^&])?(&|$)', '');
如果我们打电话给toString
,我们就会:
/&dyanmicTxtHere(\=[^&])?(?=&|$)|^dyanmicTxtHere(\=[^&])?(&|$)/
如果这不起作用,请尝试准确解释您要解析的内容。
答案 2 :(得分:1)
显然,以下内容不是正则表达式;但我认为应满足您的要求。它利用了GET查询字符串中名称 - 值对的要求,并使用简单的字符串和一些数组操作来检查传递的URL中的各种(如果有)名称 - 值对:
function removeParam(url, param) {
// checks for the existence of a '?' in the passed url:
var queryAt = url.indexOf('?') + 1;
/* function exits if:
1. no 'url' parameter was passed,
2. no 'param' parameter was passed in, or
3. the 'queryAt' variable is false, or has a falsey value */
if ((!url || !param) || !queryAt) {
return false;
}
else {
/* if the 'param' passed in wasn't found in the 'url' variable,
the function exits, returning the original url (as no modification
is required */
if (url.indexOf(param) == -1) {
return url;
}
else {
/* gets the substring of the url from the first
character *after* the '?' */
var all = url.substring(queryAt),
// creates an array of the name and value pairs
nameValues = all.split('&'),
// creating a new array
newNameValues = [],
parts;
// iterates through each name-value pair
for (var i = 0, len = nameValues.length; i < len; i++) {
// splits the name-value pair into two parts
parts = nameValues[i].split('=');
/* if the first part (the 'name' of the param) does not
matches what you're looking for then the whole name-value
pair is pushed into the 'newNameValues' array */
if (parts[0] !== param) {
newNameValues.push(nameValues[i]);
}
}
// returns the reconstructed URL
return url.substring(0, queryAt) + newNameValues.join('&');
}
}
}