简体   繁体   中英

How do I make this RegEx match if there isn't a '?' in the querystring?

I have the following RegEx to replace the entire querystring for a string with a new one:

"http://www.google.com?bar=1".replace(/\?.*/, "?foo=2")

This works only if there is a querystring. The following will not work:

"http://www.google.com".replace(/\?.*/, "?foo=2")

How do I make the RegEx match both situations?

Say or end of string :

|$

replace(/\?.*|$/, "?foo=2")

Avoid string/regex hacking for manipulating URLs in JS. There's a perfectly good URL parser built into every browser, and you can get access to it from any link element:

var a= document.createElement('a');
a.href= 'http://www.google.com/?bar=1';
a.search= '?foo=2';
alert(a.href); // http://www.google.com/?foo=2

No use for regex to me. Check if there is a ? - if not append your querystring, otherwise drop the old query string first. KISS.

捕获主机并将所有其他主机替换为所需的查询字符串。

url.replace(/([^?]+).*/, "$1?querystring");

This should work, but I'm not sure exactly what you are trying to do, I can't remember the syntax for regex in javascript so the replacestring is in python syntax but it should give you the idea.. You are matching an excaped "?" when you do "\\?" so its not going to match the second since there is no "?" in the string.

/(.*?google.com)(.*?)/  

replacestring = '\\1'+'?foo=2'

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