1

I was trying to create a 'components' system, similar to many JS frameworks. I am new to RegEx but I made something that should work for me:

/\<([A-Z])([A-Za-z])*( ?\/)?\>/g

Now, I tried to search the file for this RegEx, and replace it with the correct component,

var content = "<p>file content</p><Test />";
var components = { Test: "<b>test component</b>" };
content.split(/\<([A-Z])([A-Za-z])*( ?\/)?\>/g).forEach((comp) => {
  newCont = content.replace(
    comp,
    components[comp.substr(1, comp.length - 1)]
  );
});

but it doesn't work.
I want the code to remove all instances of <Test /> or similar, and replace them with my definition of it from components (eg. change content to "<p>file content</p><b>test component</b>").

  • 3
    *"my idea was to search the file using RegEx"* - desist, [you won't succeed](https://stackoverflow.com/a/1732454). – Marco Bonelli Mar 01 '21 at 01:14
  • 1
    @MarcoBonelli I updated the post. What I meant in my answer was that I have my Regular expression made, I just want to know how to replace instances of it with JS. –  Mar 01 '21 at 01:39

1 Answers1

1

I learned something when doing a little more research: string.replace can take a callback function as a second parameter.
With that, I found this solution:

var newCont = content.replace(
  /\<([A-Z])([A-Za-z])*( ?\/)?\>/g,
  (match) => components[match.replace(/[\<\/\> ]/g, "")] //remove <,/,>, and space characters
);