I have a string
var str = "C:\Program Files\nodejs\node_modules"
I want to replace the "C:\Program Files\" part with a hyperlink part "https://" so that the final outcome is
"https://nodejs/node_modules"
The first step to replace the slases with regex I already did it with
replace(/\\\\/gi,"/")
hence it became
"C:/Program Files/nodejs/node_modules"
So, the regex for the final outcome ,am facing difficulties.
CodePudding user response:
You might use 2 capture groups:
^[A-Z] :\\(?:[^\\\n]*\\)*([^\\\n] )\\([^\\\n] )$
^
Start of string[A-Z] :\\
Match 1 chars A-Z:
and\
(?:[^\\\n]*\\)*
Optional repetitions of any char except\
ad then match\
([^\\\n] )
Capture group 1 Match optional chars other than\
\\
Match\
([^\\\n] )
Capture group 2 the same as for capture group 1$
End of string
And replace with
https://$1/$2
See a regex demo.
const regex = /^[A-Z]:\\(?:[^\\\n]*\\)*([^\\\n] )\\([^\\\n] )$/gm;
const str = `C:\\Program Files\\nodejs\\node_modules`;
const result = str.replace(regex, `https://$1/$2`);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Find
^[A-Z]:\/[^\/] (.*)
Replace
https:/$1