0

I am currently making a HTML form upload system. I am trying to read the HTML file using fs.readFile then I'm attempting to replace the action attribute of the form tag with "/form/" + form._id, so that the form makes POST requests to this route.

I am having trouble making a regex to find the action attribute. This is what I have until now:

var newData = data.replace(/action(? *)=(? *)("|')(?=.*)("|')/g, 'action="/form/' + form._id + '/");

I know the regex is wrong. I really couldn't understand how it works. If you have an answer please write and explanation too if you don't mind. Thank you in advance.

2 Answers2

2

I don't think you need such complex regex for that

const path = "/form/1";

const str = `<form action="/test/1" method="POST" data-id="420"></form>`;

const result1 = str.replace(/action=\"(.*?)\"/gm, `action="${path}"`);
const result2 = str.replace(/(?<=action=\")(.*?)(?=\")/gm, path); // with positive lookbehind,lookahead


console.log(result1);
console.log(result2);
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
1

This works for any attribute before and after the action attribute. It also makes sure the replace only happens in a form tag.

var form = {
  _id: 123
};
var path = '/test/' + form._id;
var str = '<form method="post" action="/test/1" class="foo"></form>';

var result = str.replace(/(<form [^>]*? action=["'])([^"']*)/, '$1' + path);

console.log(result);
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20