[英]Regex remove all string start with special character
I have a string look like: 我有一个字符串看起来像:
var str = https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none
I want to remove at start ?pid=
to end. 我想从开始删除
?pid=
结束。 The result look like: 结果如下:
var str = https://sharengay.com/movie13.m3u8
I tried to: 我试过了:
str = str.replace(/^(?:?pid=)+/g, "");
But it show error like: 但是它显示如下错误:
Invalid regular expression: /^(?:?pid=)+/: Nothing to repeat
无效的正则表达式:/ ^(?:?pid =)+ /:无需重复
You may create a URL object and concatenate the origin
and the pathname
: 您可以创建一个URL对象,并将
origin
和pathname
:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"; var url = new URL(str); console.log(url.origin + url.pathname);
If you really want to do this at the string level with regex, it's simply replacing /\\?pid=.*$/
with ""
: 如果您真的想使用正则表达式在字符串级别执行此操作,只需将
/\\?pid=.*$/
替换为""
:
str = str.replace(/\?pid=.*$/, "");
That matches ?pid=
and everything that follows it ( .*
) through the end of the string ( $
). 匹配
?pid=
及其?pid=
所有内容( .*
)直至字符串( $
)的末尾。
Live Example: 现场示例:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"; str = str.replace(/\\?pid=.*$/, ""); console.log(str);
You have to escape the ?
您必须逃脱
?
and if you want to remove everything from that point you also need a .+
: 如果要从那时删除所有内容,则还需要一个
.+
:
str = str.replace(/\?pid=.+$/, "")
You can use split function to get only url without query string. 您可以使用拆分功能仅获取不含查询字符串的网址。
Here is the example. 这是例子。
var str = ' https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none '; var str =' https ://sharengay.com/movie13.m3u8?pid= 144.21.112.0& tcp= none ';
var data = str.split("?"); var data = str.split(“?”);
alert(data[0]); 警报(数据[0]);
You can simply use split(), which i think is simple and easy. 您可以简单地使用split(),我认为这很简单。
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"; str = str.split("?pid"); console.log(str[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.