Om Shankar
Om Shankar

Reputation: 8069

Convert HTML string to JavaScript text keeping indentation

I want to target or match only the first occurrence per line

Typical Scenario:

I have an HTML Structure that I am using in JavaScript.

<ul>
    <li> ABC </li>
    <li> DEF </li>
    <li> GHI <span> GHI-SPAAN </span> </li>
</ul>

To convert the above into a string, in my editor, I can simply Find & replace EOL with a '+ and beginning of line with a ' so that the code would be

var tpl = ''+
    '<ul> '+
    '<li> ABC </li> '+
    '<li> DEF </li> '+
    '<li> GHI <span> GHI-SPAAN </span> </li> '+
    '</ul> ';

But you see, I loose the indentation when I replace the beginning of line with '<

So I want to uniquely target (target only the first occurrence of < and replace with '< )

I am using KOMODO edit and Sublime Text 2

Upvotes: 1

Views: 1694

Answers (2)

Chuck Le Butt
Chuck Le Butt

Reputation: 48816

Rather than converting HTML to a JS string, it would be much better to create the elements in JS and put them in the DOM. This would give you much more control, not create such a difficult to maintain/read code, and be much faster (amongst other benefits):

var outerDiv = document.createElement("div");
outerDiv.className = "spa-shell-head";

var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";

var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";

var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";

outerDiv.appendChild(innerDivLogo);
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv);

The above creates the following:

enter image description here

https://jsfiddle.net/yfeLbhe4/

Upvotes: 0

georg
georg

Reputation: 215039

I'm not a KomodoEdit user, but I tried these replacements and they worked:

  • starting quote: replace ^(\s*)< with \1<
  • ending quote: replace >\s*$ with >' +

Hope this helps.

Upvotes: 1

Related Questions