Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only certain part in a match?

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?

like image 729
Moon Avatar asked Jul 25 '13 19:07

Moon


2 Answers

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\/))

like image 66
falsetru Avatar answered Nov 13 '22 11:11

falsetru


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 /^(.*?/).+\?/

like image 22
Explosion Pills Avatar answered Nov 13 '22 10:11

Explosion Pills