Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript正则表达式从字符串中删除子字符串_Javascript_Regex_Replace - Fatal编程技术网

javascript正则表达式从字符串中删除子字符串

javascript正则表达式从字符串中删除子字符串,javascript,regex,replace,Javascript,Regex,Replace,我有以下网址 example.com/p/deals&post_id=3 其中,post id是一个get变量。我想清理url字符串,返回的结果应该是 example.com/p/deals 我一直在尝试使用JavaScript的.replace,但由于url末尾的get变量,似乎不起作用。如何构建正则表达式以排除此子字符串。此操作不需要正则表达式。简单地从数组中提取第一个字符串: var str = "example.com/p/deals&post_id=3"; var

我有以下网址

example.com/p/deals&post_id=3
其中,post id是一个get变量。我想清理url字符串,返回的结果应该是

example.com/p/deals

我一直在尝试使用JavaScript的
.replace
,但由于url末尾的get变量,似乎不起作用。如何构建正则表达式以排除此子字符串。

此操作不需要正则表达式。简单地从数组中提取第一个字符串:

var str = "example.com/p/deals&post_id=3";
var san = str.split("&")[0];

下面是。

来匹配第一个字符之后的所有字符&您可以使用该模式

\&(**)

并简单地替换为一个空字符串

JS将是

var urlString = "example.com/p/deals&post_id=3";
var searchP = "\&(.*)" ;
var replaceP = "" ;
var rEx = new RegExp( searchP, urlString ) ;
var replacedText = sourceText.replace( rEx, replaceP ) ;