简体   繁体   中英

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. 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

You may create a URL object and concatenate the origin and the 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); 

You can use split

 var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none" var result = str.split("?pid=")[0]; console.log(result); 

If you really want to do this at the string level with regex, it's simply replacing /\\?pid=.*$/ with "" :

str = str.replace(/\?pid=.*$/, "");

That matches ?pid= and everything that follows it ( .* ) through the end of the string ( $ ).

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 data = str.split("?");

alert(data[0]);

You can simply use split(), which i think is simple and easy.

 var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"; str = str.split("?pid"); console.log(str[0]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM