I have the following string:
[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]
I wish to replace the "]" char immediately following the YouTube v= string with a ">", but can’t quite get the regex correct.
I am only able to select the complete string up to the FINAL "]", which is not what is required.
atag.replace(/https://.*?]/, etc) //Haven't worked out the grouping yet, so "etc"
3
Answers
You could match and replace on the first
[...]
:Or another slightly different version:
You could capture the part right before matching the
]
in group 1 and then match]
after it. In the replacement use group 1 to keep that part and add the character>
after it.Regex demo
For example:
Or a bit more specific and keeping the closing
]
for the tag:Regex demo
You can also use
^([url=https?://(?:www.)?youtube[^rn]]+v=[a-z0-9]{10})]([^rn[]+[/url])$
and replace it with$1>$2
:Note:
This pattern has many restrictions that you might wanna use:
^
is a start anchor.([url=https?://(?:www.)?youtube[^rn]]+v=[a-z0-9]{10})
is the capture group$1
.[url=https?://
validateshttp
orhttps
.(?:www.)?
optionally allowswww.
.youtube
only allowsyoutube
.v=[a-z0-9]{10}
checks forv
followed by 10 alphanumeric chars.–
]
: ignores the bracket you want to replace.([^rn[]+[/url])
is the second capture group.$
is an end anchor.