ExcelVBA is creating software that automatically prints HTML.
so that all link tags can be opened with a separate tag (a separate window)
I would like to convert it.And automatically
for security measures
I would like to add rel="noopener no moreferrer", but
I'm not familiar with regular expressions, so I don't know how to write patterns
I don't know.
Rewrite all a tags in HTML to open with a different tag
Could you tell me the code with a pattern?
Thank you for your cooperation.
html regular-expression vba
The regular expression can be "<a+"
and the replacement string can be "<a target="_blank""rel="noopener norferrer""
to form <a target="_blank"rel="noopener norfer" hrefode=...
Below is an example of how to develop a little and add target="_blank" after href.
In addition, if the original string contains a target or rel attribute, the decision process is not considered.
Add conditional branches, etc. as needed.
sample code
Sub button 1_Click()
Dimreg As Object
Set reg=CreateObject("VBScript.RegExp")
With reg
.Pattern="(<a.+?)(href\s*=\s*"".+?)"
.IgnoreCase=True
.Global=True
End With
Dim srcStr As String
Dim newStr As String
srcStr="<a href=""http://hoge/">a href="Do not convert here""</a>"+vbCrLf+_
"<a href=""http://fuga:1234?piyo"">/a>"+vbCrLf+_
"<a href=""http://foo""target="_blank"">In this case, duplicate targets are </a>"
newStr=reg.Replace(srcStr, "$1$2 target=""_blank""rel=""nooper noreferrer""")
MsgBox newStr
End Sub
Run Results
-------------------------------
Microsoft Excel
---------------------------
<a href="http://hoge/"target="_blank" rel="noopener noneferrer">a href="I won't convert here"</a>
<a href="http://fuga:1234?piyo" target="_blank" rel="noopener noneferrer">/a>
<a href="http://foo" target="_blank" rel="nooper no moreferrer" target="_blank">In this case, the target is duplicated </a>
---------------------------
OK.
---------------------------
© 2024 OneMinuteCode. All rights reserved.