[英]How to select only certain part in a match?
I have the following string. 我有以下字符串。
/v/dkdkd-akdoa?
I would like to replace dkdkd-akdoa
. 我想替换dkdkd-akdoa
。
My replace method looks like 我的替换方法看起来像
string.replace("v\/(.+)\?", "replace")
but it also replaces v/
. 但它也取代了v/
。 How do I replace only dkdkd-akdoa
? 我如何只更换dkdkd-akdoa
?
Try following code: 请尝试以下代码:
> '/v/dkdkd-akdoa?'.replace(/(v\/).+\?/, '$1replace')
"/v/replace"
If you want keep ?
如果你想保持?
: :
> '/v/dkdkd-akdoa?'.replace(/(v\/).+(?=\?)/, '$1replace')
"/v/replace?"
$1
reference the first group ( (v\\/)
) $1
引用第一组( (v\\/)
)
Quite simply 很简单
string.replace(/v\/.+\?/, "v/replace");
If the first part is not known you can capture and replace it: 如果第一部分未知,您可以捕获并替换它:
string.replace(/(v\/).+\?/, "$1replace");
Obviously in the second example it is known since v/
is constant. 显然,在第二个例子中,由于v/
是常数,因此是已知的。 You would potentially replace it with something like /^(.*?/).+\\?/
您可能会用/ /^(.*?/).+\\?/
You can break it up so the prefix and suffix are their own matching groups and include them in the replaced value: 您可以将其分解,以便前缀和后缀是它们自己的匹配组,并将它们包含在替换值中:
string.replace(/(v\/)(.+)(\?)/, "$1replace$3");
Or more simply treat your pattern you're replacing as a non-matching group: 或者更简单地将您正在替换的模式视为不匹配的组:
string.replace(/(v\/).+(\?)/, "$1replace$2")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.