Search code examples
javascriptjqueryhtmlasp.net-mvc-5.1

How to replace html tags with our own tags


In my MVC web application, I have a text area inside View, in that user will put HTML text so in that text, I want to replace html tags with my own custom tags.

For Example:

HTML tag:

<input type='text' name='MyList.First_Name' data-val='true' data-val-required='Please enter first name' />

Replace with:

[~TextFieldTag|MyList.First_Name|||0|data-val=>true|data-val-required=>Please enter first name|~]

Can anyone suggest what is the best approach to do this?


Solution

  • I was going to recommend a simple string replacement at first, but given the seemingly complicated nature of your replacements, that might not be the best approach.

    Probably the best approach would be to take the HTML, convert it to DOM elements, which can be done simply by throwing it into an elements innerHTML:

    document.querySelector('button').addEventListener('click', () => {
      document.querySelector('#renderSpace').innerHTML = document.querySelector('textarea').value;
    });
    Add some HTML:
    <textarea></textarea>
    <button>Press Me</button>
    <div id="renderSpace"></div>

    You can position the area you render it inside of off-screen so users don't actually see it.

    From there, I would walk the DOM tree (basically, start at the root, then look at all of its children, then their children, etc., recursively), reading off any properties that you deem appropriate and then writing your string replacement as you go along.

    That does require that they have entered valid HTML (which is generally a requirement, but can be difficult to rely on users to enter), so you'll want to have some good, user-friendly, error handling in there.