0

I have an HTML page with the following opening body tag:

<body class="one two three" id="five" data-key="value">

And I'm using lua patterns append a div to the end:

<body class="one two three" id="five" data-key="value"><div></div>

How do I do this?

Note: I've used the following before to insert a script before the head tag:

body_filter_by_lua_block {
    replacestr = "<script></script></head>"
    ngx.arg[1] = ngx.re.sub(ngx.arg[1],"</head>", replacestr)
    return
}

Therefore, if I add my div to replacestr, what do I replace ngx.re.sub(ngx.arg[1],"</head>", replacestr) with?

Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79
  • The title of your question asks how to replace an HTML tag. Your actual question is asking how to *append* something to a tag. These are two different tasks; which one do you want? – Nicol Bolas Aug 06 '17 at 01:11
  • @NicolBolas they're both the same thing. Replacing `x` with `xy` is an append. Also, [be nice](https://stackoverflow.com/help/be-nice). – Amin Shah Gilani Aug 06 '17 at 01:13
  • 1
    I don't think I've been not nice in what I've said; asking you to clarify your question is not being not nice. Also, an operation which can replace `x` with `xy` is also an operation which can replace `x` with `yz`. Whereas an operation which can append `y` to `x` can never cause `x` to be transformed into `yz`. So again, which one do you want? – Nicol Bolas Aug 06 '17 at 01:17
  • @NicolBolas Your request for a clarification didn't come across as a request for a clarification. I still think you're being nitpicky but sure, I'll change the title to an *append*. Although calling it a replacement will help people that stumble upon this question looking for replacement help. E.g. things like adding classes or `data` attributes to the `body` tag. – Amin Shah Gilani Aug 06 '17 at 01:21

1 Answers1

0

I did it.

ngx.re.sub(ngx.arg[1], '(<body[^>]*>)', "${0}" .. replacestr)
Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79
  • You should never ever work with HTML using regular expression in any halfway serious application. For example, an attribute value may contain '>' (see https://html.spec.whatwg.org/multipage/syntax.html#syntax-attributes), and your code will produce garbage in this case. – Tymur Gubayev Aug 06 '17 at 07:33
  • Hmmm, good point. Do you have an alternative to append to the body tag? – Amin Shah Gilani Aug 06 '17 at 07:34
  • You should google for an "HTML parser Lua". Maybe there is something inside that `ngx` module already. The following link looks promising: https://craigbarnes.gitlab.io/lua-gumbo/#examples – Tymur Gubayev Aug 06 '17 at 07:48