1

I want to append a word after <body> tag, it should not modify/replace anything other than just append a word. I have done something like this, is it valid do empty parenthesis fir second capture group will match everything?

/(<body[^>]*>)()/, `$1${my_variable}$2`)
naman
  • 43
  • 4

2 Answers2

0

The second capture group, designed to capture nothing, will match "nothing" - it will form a match immediately after your closed body tag. There's nothing wrong with doing this for the regex, though you might want to be wary of using [^>]* - this negated character class will gladly match across lines and grab as much input as it can. Handy for matching multi-line tags, but often very dangerous.

Also, if you're on linux and for some reason have > symbols in filenames (which is valid!) your regex will break horribly, as shown here.

That being said, valid regex or not, it's usually a bad idea to use regex with html, since HTML isn't a regular language. Also, you could accidentally summon Cthulhu.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
0
let page = "<html><body>Some info</body></html>";

page.replace("<body>", `<body>${my_variable}`);

or

page.replace(/<body>|<BODY>/, `<body>${my_variable}`);

If in the broweser you can also use document.querySelector("body").innerHTML

Also depending on which framework you're using there are better ways to accomplish this.

zendka
  • 1,074
  • 12
  • 11
  • Actually the issue is, sometimes user append space in body tag or any CSS that why it won't work – naman Sep 04 '19 at 05:30