Javascript正则表达式-匹配字符串后的所有内容

Javascript Regex - Match everything after string

本文关键字:正则表达式 -匹 字符串 Javascript      更新时间:2023-09-26

我试图使用JS regex在我的url中删除字符串后的一切。例如www.myurl/one/two/three/?a=b&c=d,我想删除字符串"three/"之后的所有内容。我怎么写一个正则表达式来匹配这个呢?

试试这个:

function getPathFromUrl(url) {
  return url.split("?")[0];
}
var url = 'www.myurl/one/two/three/?a=b&c=d';
var result = getPathFromUrl(url);
alert(result);

有一个快速的方法。

var str = 'www.myurl/one/two/three/?a=b&c=d'
var newStr = str.replace(/(.*'/three'/).*/, '$1')
alert(newStr)

使用内置功能来操作url。

var a = document.createElement('a');
a.href = "http://www.myurl/one/two/three/?a=b&c=d";
a.search = '';
console.log(a.href);

指出:

  1. a元素的search属性是指以问号开头的部分

  2. 这里需要http://;否则,该URL将被解释为相对于当前URL

如果您更喜欢使用regexp,那么您可以擦除以问号开头的所有内容:

"www.myurl/one/two/three/?a=b&c=d".replace(/'?.*/, '')

或者,您可以匹配您想要保留的内容,例如的所有内容,使用:

"www.myurl/one/two/three/?a=b&c=d".match(/.*(?='?)/)[0]

您需要[0],因为match返回一个数组,其第一个元素是整个匹配。这里的?=是一个前瞻性。实际上这和

是一样的
"www.myurl/one/two/three/?a=b&c=d".match(/[^?]+/)[0]

或者,如果你想匹配three/:

"www.myurl/one/two/three/?a=b&c=d".match(/.*three'//)[0]

或者基本上使用String和Array方法:

var string = "www.myurl/one/two/three/?a=b&c=d";
var array = string.split('/');
array.pop();
var result = array.join("/");
console.log(result); //www.myurl/one/two/three