I have the following string.
/v/dkdkd-akdoa?
I would like to replace dkdkd-akdoa
.
My replace method looks like
string.replace("v\/(.+)\?", "replace")
but it also replaces v/
. How do I replace only 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\/)
)
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. You would potentially replace it with something like /^(.*?/).+\?/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With